import { useEffect, useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  useAssignTicket,
  useReplyTicket,
  useTicket,
  useTicketStatuses,
  useUpdateTicketStatusMutation,
} from "../core/_hooks";
import { TicketStatus } from "../core/_models";
import { PageContainer, PageTitle, SectionTitle, Label } from "@/components/ui/Typography";
import { Button } from "@/components/ui/Button";
import { FileUploader } from "@/components/ui/FileUploader";
import { useFileUpload, useFileDelete } from "@/hooks/useFileUpload";
import { Input } from "@/components/ui/Input";
import {
  ArrowRight,
  MessageSquare,
  Send,
  UserCheck,
  Paperclip,
} from "lucide-react";

const statusColor = (status?: TicketStatus) => {
  if (!status) return "bg-gray-100 text-gray-800";
  if (status.slug === "pending") return "bg-yellow-100 text-yellow-800";
  if (status.slug === "answered") return "bg-green-100 text-green-800";
  if (status.slug === "closed") return "bg-gray-200 text-gray-800";
  return "bg-primary-50 text-primary-700";
};

const TicketDetailPage = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const { data: ticket, isLoading, error } = useTicket(id);
  const { data: statuses } = useTicketStatuses({ activeOnly: true });
  const { mutate: sendReply, isPending: isReplying } = useReplyTicket();
  const { mutate: updateStatus, isPending: isUpdatingStatus } =
    useUpdateTicketStatusMutation();
  const { mutate: assignTicket, isPending: isAssigning } = useAssignTicket();
  const { mutateAsync: uploadFile } = useFileUpload();
  const { mutate: deleteFile } = useFileDelete();

  const [statusId, setStatusId] = useState<number | undefined>();
  const [assignedValue, setAssignedValue] = useState<string>("");
  const [message, setMessage] = useState("");
  const [attachments, setAttachments] = useState<
    { id: string; url: string }[]
  >([]);
  const [uploaderKey, setUploaderKey] = useState(0);
  const [isUploading, setIsUploading] = useState(false);

  useEffect(() => {
    if (ticket?.status?.id) {
      setStatusId(ticket.status.id);
    }
    if (ticket?.assigned_to) {
      setAssignedValue(ticket.assigned_to.toString());
    } else {
      setAssignedValue("");
    }
  }, [ticket]);

  const infoItems = useMemo(
    () => [
      {
        label: "وضعیت",
        value: (
          <span
            className={`px-2 py-1 rounded-full text-xs font-medium ${statusColor(
              ticket?.status
            )}`}
          >
            {ticket?.status?.name || "-"}
          </span>
        ),
      },
      {
        label: "دپارتمان",
        value: ticket?.department?.name || "-",
      },
      {
        label: "موضوع",
        value: ticket?.subject?.name || "-",
      },
      {
        label: "مسئول",
        value: ticket?.assigned_user
          ? `${ticket.assigned_user.first_name || ""} ${
              ticket.assigned_user.last_name || ""
            }`.trim() || ticket.assigned_user.username
          : ticket?.assigned_to || "-",
      },
      {
        label: "تاریخ ایجاد",
        value: ticket?.created_at || "-",
      },
      {
        label: "آخرین بروزرسانی",
        value: ticket?.updated_at || "-",
      },
    ],
    [ticket]
  );

  const handleStatusUpdate = () => {
    if (!id || !statusId) return;
    updateStatus({
      ticketId: id,
      payload: { status_id: statusId },
    });
  };

  const handleAssign = () => {
    if (!id || !assignedValue) return;
    assignTicket({
      ticketId: id,
      payload: { assigned_to: Number(assignedValue) },
    });
  };

  const handleFileUpload = async (file: File) => {
    const result = await uploadFile(file);
    setAttachments((prev) => [...prev, result]);
    return result;
  };

  const handleFileRemove = (fileId: string) => {
    setAttachments((prev) => prev.filter((file) => file.id !== fileId));
    deleteFile(fileId);
  };

  const handleReply = () => {
    if (!id || !message.trim()) return;
    sendReply(
      {
        ticketId: id,
        payload: {
          message: message.trim(),
          file_ids: attachments
            .map((file) => Number(file.id))
            .filter((fileId) => !Number.isNaN(fileId)),
        },
      },
      {
        onSuccess: () => {
          setMessage("");
          setAttachments([]);
          setUploaderKey((prev) => prev + 1);
        },
      }
    );
  };

  if (isLoading) {
    return (
      <PageContainer>
        <div className="space-y-6 animate-pulse">
          <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-48"></div>
          <div className="card p-6 space-y-6">
            {[...Array(5)].map((_, i) => (
              <div key={i}>
                <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-32 mb-2"></div>
                <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded"></div>
              </div>
            ))}
          </div>
        </div>
      </PageContainer>
    );
  }

  if (error || !ticket) {
    return (
      <PageContainer>
        <div className="card p-6 text-center text-red-600 dark:text-red-400">
          خطا در بارگذاری تیکت
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          <Button
            variant="secondary"
            className="flex items-center gap-2"
            onClick={() => navigate(-1)}
          >
            <ArrowRight className="h-4 w-4" />
            بازگشت
          </Button>
          <PageTitle>
            تیکت {ticket.ticket_number} - {ticket.title}
          </PageTitle>
        </div>
      </div>

      <div className="card p-6 space-y-6">
        <SectionTitle>اطلاعات تیکت</SectionTitle>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {infoItems.map((item) => (
            <div
              key={item.label}
              className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg"
            >
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {item.label}
              </p>
              <div className="text-base font-medium text-gray-900 dark:text-gray-100 mt-1">
                {item.value}
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="card p-6 space-y-4">
        <SectionTitle>مدیریت وضعیت و مسئول</SectionTitle>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="space-y-3">
            <Label>تغییر وضعیت</Label>
            <select
              value={statusId || ""}
              onChange={(e) =>
                setStatusId(e.target.value ? Number(e.target.value) : undefined)
              }
              className="w-full px-3 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
            >
              <option value="">انتخاب وضعیت</option>
              {statuses?.map((status) => (
                <option key={status.id} value={status.id}>
                  {status.name}
                </option>
              ))}
            </select>
            <Button
              variant="primary"
              onClick={handleStatusUpdate}
              disabled={!statusId || isUpdatingStatus}
              loading={isUpdatingStatus}
            >
              به‌روزرسانی وضعیت
            </Button>
          </div>
          <div className="space-y-3">
            <Label>اختصاص به</Label>
            <Input
              placeholder="شناسه کاربر مسئول"
              type="number"
              value={assignedValue}
              onChange={(e) => setAssignedValue(e.target.value)}
            />
            <Button
              variant="primary"
              onClick={handleAssign}
              disabled={!assignedValue || isAssigning}
              loading={isAssigning}
              className="flex items-center gap-2"
            >
              <UserCheck className="h-4 w-4" />
              ثبت مسئول
            </Button>
          </div>
        </div>
      </div>

      <div className="card p-6 space-y-4">
        <SectionTitle className="flex items-center gap-2">
          <MessageSquare className="h-5 w-5" />
          تاریخچه پیام‌ها
        </SectionTitle>
        <div className="space-y-4">
          {ticket.messages && ticket.messages.length > 0 ? (
            ticket.messages.map((messageItem) => {
              const isAdmin = messageItem.sender_type === "admin";
              return (
                <div
                  key={messageItem.id}
                  className={`flex ${isAdmin ? "justify-end" : "justify-start"}`}
                >
                  <div
                    className={`max-w-3xl w-full sm:w-auto space-y-2 ${
                      isAdmin ? "text-white" : "text-gray-900 dark:text-gray-100"
                    }`}
                  >
                    <div
                      className={`rounded-2xl px-4 py-3 shadow-sm transition-colors ${
                        isAdmin
                          ? "bg-primary-600 rounded-tl-2xl rounded-br-md"
                          : "bg-gray-100 dark:bg-gray-700 rounded-tr-2xl rounded-bl-md"
                      }`}
                    >
                      <div className="flex items-center justify-between text-xs opacity-80">
                        <span>{isAdmin ? "شما" : "کاربر"}</span>
                        <span>{messageItem.created_at}</span>
                      </div>
                      <p className="mt-2 text-sm leading-relaxed">
                        {messageItem.message}
                      </p>
                      {messageItem.attachments &&
                        messageItem.attachments.length > 0 && (
                          <div className="mt-3 flex flex-wrap gap-2">
                            {messageItem.attachments.map((attachment) => (
                              <a
                                key={attachment.id}
                                href={attachment.url}
                                target="_blank"
                                rel="noreferrer"
                                className={`inline-flex items-center gap-1 rounded-full border px-3 py-1 text-xs ${
                                  isAdmin
                                    ? "border-white/30 text-white hover:bg-white/10"
                                    : "border-gray-300 dark:border-gray-500 text-primary-600 dark:text-primary-300 hover:bg-white/40 dark:hover:bg-gray-600"
                                }`}
                              >
                                <Paperclip className="h-3.5 w-3.5" />
                                {attachment.original_name ||
                                  `فایل ${attachment.id}`}
                              </a>
                            ))}
                          </div>
                        )}
                    </div>
                  </div>
                </div>
              );
            })
          ) : (
            <div className="text-center text-gray-500 dark:text-gray-400">
              پیامی ثبت نشده است
            </div>
          )}
        </div>
      </div>

      <div className="card p-6 space-y-4">
        <SectionTitle>ارسال پاسخ جدید</SectionTitle>
        <div className="space-y-4">
          <div>
            <Label>متن پیام</Label>
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              rows={4}
              className="w-full border border-gray-300 dark:border-gray-600 rounded-lg p-3 focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
              placeholder="پاسخ خود را بنویسید"
            />
          </div>
          <FileUploader
            key={uploaderKey}
            onUpload={handleFileUpload}
            onRemove={handleFileRemove}
            acceptedTypes={["image/*", "application/*"]}
            maxFileSize={25 * 1024 * 1024}
            maxFiles={5}
            label="ضمائم"
            description="حداکثر ۵ فایل با مجموع حجم ۲۵ مگابایت"
            onUploadStart={() => setIsUploading(true)}
            onUploadComplete={() => setIsUploading(false)}
          />
          <Button
            variant="primary"
            className="flex items-center gap-2"
            onClick={handleReply}
            disabled={!message.trim() || isReplying || isUploading}
            loading={isReplying}
          >
            <Send className="h-4 w-4" />
            ارسال پاسخ
          </Button>
        </div>
      </div>
    </PageContainer>
  );
};

export default TicketDetailPage;

