"use client";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { useParams } from "next/navigation";
import { Link } from "@/i18n/routing";
import { apiGet, apiPost } from "@/lib/api/client";
import { useApiError } from "@/lib/use-api-error";
import { useAuthStore } from "@/lib/stores/auth.store";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { notify } from "@/lib/notify";
import {
  isTicketClosed,
  TicketStatusBadge,
  type TicketStatus,
} from "@/components/support/ticket-status-badge";

type SupportTicket = {
  id: string;
  subject: string;
  status: TicketStatus;
  priority: string;
  updatedAt: string;
  messageCount: number;
};

type SupportTicketDetail = {
  ticket: SupportTicket & { updatedAt: string };
  messages: {
    id: string;
    senderKind: string;
    senderName?: string | null;
    body: string;
    createdAt: string;
  }[];
};

function formatDate(iso: string) {
  try {
    return new Date(iso).toLocaleString("fa-IR", {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return iso;
  }
}

export function SupportScreen() {
  const t = useTranslations("support");
  const apiError = useApiError();
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const [subject, setSubject] = useState("");
  const [body, setBody] = useState("");
  const qc = useQueryClient();

  const {
    data: tickets = [],
    isLoading,
    isError,
    error,
    refetch,
  } = useQuery({
    queryKey: ["support", cafeId],
    queryFn: () => apiGet<SupportTicket[]>(`/api/cafes/${cafeId}/support/tickets`),
    enabled: !!cafeId,
  });

  const create = useMutation({
    mutationFn: () =>
      apiPost<SupportTicketDetail>(`/api/cafes/${cafeId}/support/tickets`, {
        subject,
        body,
        priority: "Normal",
      }),
    onSuccess: (detail) => {
      setSubject("");
      setBody("");
      qc.setQueryData<SupportTicket[]>(["support", cafeId], (prev = []) => {
        const row: SupportTicket = {
          id: detail.ticket.id,
          subject: detail.ticket.subject,
          status: detail.ticket.status,
          priority: detail.ticket.priority,
          updatedAt: detail.ticket.updatedAt,
          messageCount: detail.messages.length,
        };
        if (prev.some((x) => x.id === row.id)) return prev;
        return [row, ...prev];
      });
      void qc.invalidateQueries({ queryKey: ["support", cafeId] });
      notify.success(t("created"));
    },
    onError: () => notify.error(t("createFailed")),
  });

  if (!cafeId) return null;

  return (
    <div className="mx-auto max-w-3xl space-y-4">
      <div>
        <h1 className="text-lg font-medium">{t("title")}</h1>
        <p className="text-sm text-muted-foreground">{t("subtitle")}</p>
      </div>

      <Card className="rounded-xl border border-border/80">
        <CardHeader>
          <CardTitle className="text-base">{t("newTicket")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-2">
          <Input
            value={subject}
            onChange={(e) => setSubject(e.target.value)}
            placeholder={t("subject")}
          />
          <textarea
            className="min-h-24 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
            value={body}
            onChange={(e) => setBody(e.target.value)}
            placeholder={t("message")}
          />
          <Button
            disabled={!subject.trim() || !body.trim() || create.isPending}
            onClick={() => create.mutate()}
          >
            {t("submit")}
          </Button>
        </CardContent>
      </Card>

      <p className="text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground">
        {t("myTickets")}
      </p>
      {isError ? (
        <Card className="rounded-xl border border-destructive/30 p-4 text-sm text-destructive">
          <p>{apiError(error, t("loadFailed"))}</p>
          <Button variant="outline" size="sm" className="mt-2" onClick={() => void refetch()}>
            {t("retry")}
          </Button>
        </Card>
      ) : isLoading ? (
        <p className="text-sm text-muted-foreground">{t("loading")}</p>
      ) : tickets.length === 0 ? (
        <Card className="rounded-xl border border-dashed p-8 text-center text-sm text-muted-foreground">
          {t("empty")}
        </Card>
      ) : (
        <div className="space-y-2">
          {tickets.map((ticket) => (
            <Link key={ticket.id} href={`/support/${ticket.id}`}>
              <Card className="rounded-xl border p-4 transition hover:border-primary">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <p className="font-medium">{ticket.subject}</p>
                  <TicketStatusBadge status={ticket.status} />
                </div>
                <p className="mt-2 text-xs text-muted-foreground">
                  {ticket.messageCount} {t("messages")} · {formatDate(ticket.updatedAt)}
                </p>
              </Card>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}

export function SupportTicketDetailScreen() {
  const t = useTranslations("support");
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const params = useParams();
  const ticketId = params.ticketId as string;
  const [reply, setReply] = useState("");
  const qc = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ["support", cafeId, ticketId],
    queryFn: () =>
      apiGet<SupportTicketDetail>(`/api/cafes/${cafeId}/support/tickets/${ticketId}`),
    enabled: !!cafeId && !!ticketId,
  });

  const closed = data ? isTicketClosed(data.ticket.status) : false;

  const send = useMutation({
    mutationFn: () =>
      apiPost<SupportTicketDetail>(
        `/api/cafes/${cafeId}/support/tickets/${ticketId}/messages`,
        { body: reply }
      ),
    onSuccess: () => {
      setReply("");
      void qc.invalidateQueries({ queryKey: ["support", cafeId, ticketId] });
      void qc.invalidateQueries({ queryKey: ["support", cafeId] });
      notify.success(t("replySent"));
    },
    onError: () => notify.error(t("replyFailed")),
  });

  if (isLoading) return <p className="text-sm text-muted-foreground">{t("loading")}</p>;
  if (!data) return <p className="text-sm text-muted-foreground">{t("notFound")}</p>;

  return (
    <div className="mx-auto max-w-2xl space-y-4">
      <Link href="/support" className="text-sm text-primary">
        ← {t("back")}
      </Link>
      <Card className="rounded-xl border p-4">
        <div className="flex flex-wrap items-start justify-between gap-2">
          <h1 className="text-lg font-medium">{data.ticket.subject}</h1>
          <TicketStatusBadge status={data.ticket.status} />
        </div>
        {closed ? (
          <p className="mt-2 text-sm text-muted-foreground">{t("closedHint")}</p>
        ) : null}
      </Card>
      <div className="space-y-2">
        {data.messages.map((m) => (
          <Card
            key={m.id}
            className={`rounded-xl border p-3 ${
              m.senderKind === "Merchant"
                ? "border-primary/20 bg-[#E1F5EE]/30 ms-8"
                : "border-border/80 me-8"
            }`}
          >
            <p className="text-xs font-medium text-muted-foreground">
              {m.senderKind === "Admin" ? t("fromAdmin") : t("fromYou")}
              {m.senderName ? ` · ${m.senderName}` : ""}
            </p>
            <p className="mt-1 text-sm whitespace-pre-wrap">{m.body}</p>
            <p className="mt-2 text-[10px] text-muted-foreground">{formatDate(m.createdAt)}</p>
          </Card>
        ))}
      </div>
      {!closed ? (
        <Card className="space-y-2 rounded-xl border p-4">
          <textarea
            className="min-h-20 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
            value={reply}
            onChange={(e) => setReply(e.target.value)}
            placeholder={t("reply")}
          />
          <Button disabled={!reply.trim() || send.isPending} onClick={() => send.mutate()}>
            {t("send")}
          </Button>
        </Card>
      ) : null}
    </div>
  );
}
