"use client";

import Link from "next/link";
import { useParams } from "next/navigation";
import { useState } from "react";
import { ArrowLeft, Send, UserCircle2, Wrench } from "lucide-react";
import { api, useApi } from "@/lib/client";
import { Badge, Button, Card, CardHeader, Field, KeyValue, PageHeader, Select, Textarea, useToast } from "@/components/ui";
import { formatDateTime } from "@/lib/utils";

interface Message {
  id: number;
  authorType: string;
  authorName: string | null;
  message: string;
  createdAt: string;
}

export default function TicketDetailPage() {
  const params = useParams<{ id: string }>();
  const toast = useToast();
  const { data, loading, reload } = useApi<{
    ticket: { id: number; ticketNo: string; subject: string; category: string; priority: string; status: string; createdAt: string; closedAt: string | null; message: string };
    customer: { id: number; name: string; customerCode: string; mobile: string; email: string | null; status: string };
    assignee: string | null;
    messages: Message[];
  }>(`/api/tickets/${params.id}`);
  const { data: staffData } = useApi<{ staff: { id: number; name: string }[] }>("/api/tickets?pageSize=1");
  const [reply, setReply] = useState("");
  const [busy, setBusy] = useState(false);

  const update = async (payload: Record<string, unknown>) => {
    setBusy(true);
    try {
      await api(`/api/tickets/${params.id}`, { method: "PUT", json: payload });
      toast.push("Ticket updated", "success");
      void reload();
    } catch (err) {
      toast.push(err instanceof Error ? err.message : "Update failed", "error");
    } finally {
      setBusy(false);
    }
  };

  if (loading && !data) return <div className="skeleton h-96 rounded-2xl" />;

  return (
    <>
      <PageHeader
        title={`${data?.ticket.ticketNo ?? "Ticket"} — ${data?.ticket.subject ?? ""}`}
        subtitle={`Raised by ${data?.customer.name ?? ""} (${data?.customer.customerCode ?? ""})`}
        icon={<ArrowLeft className="h-5 w-5" />}
        actions={
          <>
            <Link href="/admin/tickets">
              <Button variant="secondary" size="sm">
                Back
              </Button>
            </Link>
            <Link href={`/admin/customers/${data?.customer.id}`}>
              <Button variant="secondary" size="sm">
                Customer profile
              </Button>
            </Link>
          </>
        }
      />

      <div className="grid gap-4 xl:grid-cols-3">
        <Card className="xl:col-span-2">
          <CardHeader title="Conversation" subtitle={`${data?.messages.length ?? 0} message(s)`} icon={<Wrench className="h-4 w-4" />} />
          <ul className="space-y-3 p-4">
            {(data?.messages ?? []).map((m) => (
              <li key={m.id} className={`flex gap-3 ${m.authorType === "staff" ? "flex-row-reverse" : ""}`}>
                <span className={`grid h-9 w-9 shrink-0 place-items-center rounded-xl ${m.authorType === "staff" ? "bg-brand-500/20 text-brand-400" : "bg-white/8 text-slate-300"}`}>
                  {m.authorType === "staff" ? <Wrench className="h-4 w-4" /> : <UserCircle2 className="h-4 w-4" />}
                </span>
                <div className={`max-w-[80%] rounded-2xl border px-3.5 py-2.5 ${m.authorType === "staff" ? "border-brand-400/25 bg-brand-500/10" : "border-white/8 bg-white/4"}`}>
                  <p className="whitespace-pre-wrap text-sm text-slate-100">{m.message}</p>
                  <p className="mt-1 text-[10px] text-slate-500">
                    {m.authorName ?? m.authorType} · {formatDateTime(m.createdAt)}
                  </p>
                </div>
              </li>
            ))}
          </ul>
          <div className="border-t border-white/8 p-4">
            <Textarea value={reply} onChange={(e) => setReply(e.target.value)} placeholder="Write a reply…" />
            <div className="mt-2 flex justify-end">
              <Button
                loading={busy}
                icon={<Send className="h-4 w-4" />}
                onClick={async () => {
                  if (!reply.trim()) return;
                  setBusy(true);
                  try {
                    await api(`/api/tickets/${params.id}/messages`, { method: "POST", json: { message: reply } });
                    setReply("");
                    toast.push("Reply posted", "success");
                    void reload();
                  } catch (err) {
                    toast.push(err instanceof Error ? err.message : "Reply failed", "error");
                  } finally {
                    setBusy(false);
                  }
                }}
              >
                Send reply
              </Button>
            </div>
          </div>
        </Card>

        <div className="space-y-4">
          <Card>
            <CardHeader title="Ticket details" icon={<Badge value={data?.ticket.status} />} />
            <div className="p-4">
              <KeyValue
                items={[
                  { label: "Ticket", value: data?.ticket.ticketNo },
                  { label: "Category", value: data?.ticket.category },
                  { label: "Priority", value: <Badge value={data?.ticket.priority} /> },
                  { label: "Status", value: <Badge value={data?.ticket.status} /> },
                  { label: "Created", value: formatDateTime(data?.ticket.createdAt) },
                  { label: "Closed", value: data?.ticket.closedAt ? formatDateTime(data.ticket.closedAt) : "—" },
                  { label: "Assignee", value: data?.assignee ?? "Unassigned" },
                  { label: "Customer mobile", value: data?.customer.mobile },
                  { label: "Customer email", value: data?.customer.email ?? "—" },
                ]}
              />
            </div>
          </Card>

          <Card>
            <CardHeader title="Workflow" subtitle="Update status, priority or assignee" />
            <div className="space-y-3 p-4">
              <Field label="Status">
                <Select value={data?.ticket.status ?? "open"} onChange={(e) => void update({ status: e.target.value })}>
                  {["open", "pending", "processing", "resolved", "closed"].map((s) => (
                    <option key={s} value={s}>
                      {s}
                    </option>
                  ))}
                </Select>
              </Field>
              <Field label="Priority">
                <Select value={data?.ticket.priority ?? "medium"} onChange={(e) => void update({ priority: e.target.value })}>
                  {["low", "medium", "high", "urgent"].map((s) => (
                    <option key={s} value={s}>
                      {s}
                    </option>
                  ))}
                </Select>
              </Field>
              <Field label="Assignee">
                <Select value="" onChange={(e) => e.target.value && void update({ assignedTo: Number(e.target.value) })}>
                  <option value="">Reassign…</option>
                  {(staffData?.staff ?? []).map((s) => (
                    <option key={s.id} value={s.id}>
                      {s.name}
                    </option>
                  ))}
                </Select>
              </Field>
            </div>
          </Card>
        </div>
      </div>
    </>
  );
}
