"use client";
// src/app/tickets/[id]/page.tsx
import { useEffect, useState, useCallback } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import { AppShell } from "@/components/layout/AppShell";
import { Button, Card, CardHeader, CardTitle, CardContent, ConfirmDialog, PriorityBadge } from "@/components/ui/index";
import {
  formatDate, formatDateTime, formatRelativeTime, getLabel,
  TICKET_STATUS_LABELS, TICKET_STATUS_LABELS_AR, TICKET_STATUS_COLORS,
  TICKET_TYPE_LABELS, TICKET_TYPE_LABELS_AR, TICKET_CHANNEL_LABELS, TICKET_CHANNEL_LABELS_AR,
} from "@/lib/utils";
import { toast } from "sonner";
import { useAuth } from "@/hooks/useAuth";
import { hasPermission } from "@/lib/permissions";
import {
  Trash2, Loader2, AlertCircle,
  Clock, CheckCircle2, Send, Lock,
} from "lucide-react";
import { useLanguage } from "@/i18n/LanguageContext";
import { EntityCustomFieldsReadOnly } from "@/components/custom-fields/EntityCustomFieldsSection";

const SLA_WARN_MINUTES = 30; // warn if less than 30min remaining

export default function TicketDetailPage() {
  const { id } = useParams() as { id: string };
  const router = useRouter();
  const { user } = useAuth();
  const { t, language } = useLanguage();
  const [ticket, setTicket] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [commentBody, setCommentBody] = useState("");
  const [isSubmittingComment, setIsSubmittingComment] = useState(false);

  const canDelete = user && hasPermission(user.role, "tickets:delete");

  const fetchTicket = useCallback(async () => {
    setIsLoading(true);
    try {
      const res = await fetch(`/api/tickets/${id}`);
      if (!res.ok) throw new Error("Not found");
      setTicket((await res.json()).data);
    } catch (e: any) { setError(e.message); }
    finally { setIsLoading(false); }
  }, [id]);

  useEffect(() => { void fetchTicket(); }, [fetchTicket]);

  const handleStatusChange = async (newStatus: string) => {
    try {
      const res = await fetch(`/api/tickets/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: newStatus }),
      });
      if (!res.ok) throw new Error((await res.json()).error);
      toast.success(
        t("tickets.toastStatusUpdated", {
          status: getLabel(TICKET_STATUS_LABELS, TICKET_STATUS_LABELS_AR, newStatus, language),
        })
      );
      fetchTicket();
    } catch (e: any) { toast.error(e.message); }
  };

  const handleAddComment = async () => {
    if (!commentBody.trim()) return;
    setIsSubmittingComment(true);
    try {
      const res = await fetch(`/api/tickets/${id}/comments`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ body: commentBody }),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? "Failed");
      setCommentBody("");
      toast.success(t("tickets.toastCommentAdded"));
      fetchTicket();
    } catch (e: any) { toast.error(e.message); }
    finally { setIsSubmittingComment(false); }
  };

  const handleDelete = async () => {
    setIsDeleting(true);
    try {
      await fetch(`/api/tickets/${id}`, { method: "DELETE" });
      toast.success(t("tickets.toastDeletedOk"));
      router.push("/tickets");
    } catch { toast.error(t("tickets.loadError")); }
    finally { setIsDeleting(false); }
  };

  const getSlaStatus = () => {
    if (!ticket?.resolutionDue) return null;
    const now = new Date();
    const due = new Date(ticket.resolutionDue);
    const diffMin = (due.getTime() - now.getTime()) / 60000;
    if (ticket.status === "RESOLVED" || ticket.status === "CLOSED") return { label: t("tickets.slaLabelResolved"), color: "text-green-600", icon: <CheckCircle2 className="w-4 h-4" /> };
    if (diffMin < 0) return { label: t("tickets.slaLabelOverdue"), color: "text-red-600", icon: <AlertCircle className="w-4 h-4" /> };
    if (diffMin < SLA_WARN_MINUTES) return { label: t("tickets.slaMinutesRemaining", { n: Math.round(diffMin) }), color: "text-amber-600", icon: <Clock className="w-4 h-4" /> };
    return { label: `${t("tickets.slaDuePrefix")} ${formatDateTime(ticket.resolutionDue)}`, color: "text-muted-foreground", icon: <Clock className="w-4 h-4" /> };
  };

  if (isLoading) return <AppShell breadcrumbs={[{ label: t("tickets.title"), href: "/tickets" }, { label: t("common.breadcrumbLoading") }]}><div className="flex justify-center h-64 items-center"><Loader2 className="w-8 h-8 animate-spin text-primary" /></div></AppShell>;
  if (error || !ticket) return <AppShell breadcrumbs={[{ label: t("tickets.title"), href: "/tickets" }, { label: t("common.breadcrumbNotFound") }]}><div className="flex flex-col items-center justify-center h-64 gap-4"><AlertCircle className="w-12 h-12 text-destructive" /><p>{error ?? t("error.notFound")}</p><Button variant="outline" onClick={() => router.push("/tickets")}>{t("common.back")}</Button></div></AppShell>;

  const slaStatus = getSlaStatus();

  const statusTransitions: Record<string, string[]> = {
    NEW: ["OPEN", "IN_PROGRESS"],
    OPEN: ["IN_PROGRESS", "RESOLVED", "CLOSED"],
    IN_PROGRESS: ["WAITING_CUSTOMER", "RESOLVED"],
    WAITING_CUSTOMER: ["IN_PROGRESS", "RESOLVED"],
    RESOLVED: ["CLOSED", "OPEN"],
    CLOSED: ["OPEN"],
  };
  const nextStatuses = statusTransitions[ticket.status] ?? [];

  return (
    <AppShell breadcrumbs={[{ label: t("tickets.title"), href: "/tickets" }, { label: ticket.ticketNumber }]}>
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-6">
        <div>
          <div className="flex items-center gap-3 flex-wrap mb-1">
            <span className="font-mono text-sm font-bold text-muted-foreground">{ticket.ticketNumber}</span>
            <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${TICKET_STATUS_COLORS[ticket.status] ?? "bg-gray-100"}`}>
              {getLabel(TICKET_STATUS_LABELS, TICKET_STATUS_LABELS_AR, ticket.status, language)}
            </span>
            <PriorityBadge priority={ticket.priority} />
          </div>
          <h1 className="text-xl font-bold text-foreground">{ticket.subject}</h1>
          <p className="text-sm text-muted-foreground mt-1">
            {getLabel(TICKET_TYPE_LABELS, TICKET_TYPE_LABELS_AR, ticket.type, language)} · {t("tickets.viaChannel")}{" "}
            {getLabel(TICKET_CHANNEL_LABELS, TICKET_CHANNEL_LABELS_AR, ticket.channel, language)} · {formatRelativeTime(ticket.createdAt, language)}
          </p>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          {nextStatuses.map((s) => (
            <Button key={s} variant="outline" size="sm" onClick={() => handleStatusChange(s)}>
              {getLabel(TICKET_STATUS_LABELS, TICKET_STATUS_LABELS_AR, s, language)}
            </Button>
          ))}
          {canDelete && (
            <Button variant="destructive" size="sm" onClick={() => setDeleteOpen(true)}>
              <Trash2 className="w-4 h-4" />
            </Button>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left: description + comments */}
        <div className="lg:col-span-2 space-y-6">
          {/* Description */}
          <Card>
            <CardHeader><CardTitle>{t("common.description")}</CardTitle></CardHeader>
            <CardContent>
              <p className="text-sm text-foreground whitespace-pre-wrap leading-relaxed">
                {ticket.description}
              </p>
            </CardContent>
          </Card>

          {/* Comments */}
          <Card>
            <CardHeader>
              <CardTitle>{t("tickets.commentsTitle")} ({ticket.comments?.length ?? 0})</CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              {ticket.comments?.length === 0 ? (
                <div className="py-8 text-center text-muted-foreground text-sm">{t("tickets.noCommentsYet")}</div>
              ) : (
                <div className="divide-y divide-border">
                  {ticket.comments?.map((c: any) => (
                    <div key={c.id} className={`px-6 py-4 ${c.isInternal ? "bg-amber-50/50 dark:bg-amber-900/10" : ""}`}>
                      <div className="flex items-start gap-3">
                        <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary text-xs font-bold flex-shrink-0">
                          {c.authorName?.[0] ?? "?"}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="text-sm font-medium">{c.authorName ?? t("tickets.unknownAuthor")}</span>
                            {c.isInternal && (
                              <span className="flex items-center gap-1 text-xs text-amber-600 font-medium">
                                <Lock className="w-3 h-3" /> {t("tickets.internalNoteBadge")}
                              </span>
                            )}
                            <span className="text-xs text-muted-foreground ml-auto">{formatRelativeTime(c.createdAt, language)}</span>
                          </div>
                          <p className="text-sm text-foreground whitespace-pre-wrap">{c.body}</p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* Add comment */}
              <div className="px-6 py-4 border-t border-border">
                <textarea
                  value={commentBody}
                  onChange={(e) => setCommentBody(e.target.value)}
                  placeholder={t("tickets.detailReplyPlaceholder")}
                  className="w-full rounded-lg border border-input bg-background text-sm p-3 focus:outline-none focus:ring-2 focus:ring-ring resize-none"
                  rows={3}
                />
                <div className="flex items-center justify-end mt-3">
                  <Button
                    size="sm" onClick={handleAddComment}
                    loading={isSubmittingComment} disabled={!commentBody.trim()}
                  >
                    <Send className="w-4 h-4" /> {t("tickets.addComment")}
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Right sidebar */}
        <div className="space-y-6">
          {/* SLA */}
          {slaStatus && (
            <Card>
              <CardHeader><CardTitle>{t("tickets.slaCardTitle")}</CardTitle></CardHeader>
              <CardContent className="space-y-3">
                <div className={`flex items-center gap-2 ${slaStatus.color}`}>
                  {slaStatus.icon}
                  <span className="text-sm font-medium">{slaStatus.label}</span>
                </div>
                {ticket.firstResponseDue && (
                  <div className="text-xs text-muted-foreground">
                    <span className="font-medium">{t("tickets.firstResponseDueLabel")}:</span> {formatDateTime(ticket.firstResponseDue)}
                  </div>
                )}
                {ticket.firstResponseAt && (
                  <div className="text-xs text-green-600">
                    ✓ {t("tickets.respondedLabel")}: {formatDateTime(ticket.firstResponseAt)}
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Details */}
          <Card>
            <CardHeader><CardTitle>{t("tickets.ticketDetailsCard")}</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div>
                <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide mb-1">{t("common.assignedTo")}</p>
                <p className="text-sm font-medium">{ticket.assignedTo?.name ?? t("common.unassigned")}</p>
              </div>
              {ticket.team && (
                <div>
                  <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide mb-1">{t("tickets.teamLabel")}</p>
                  <p className="text-sm font-medium">{ticket.team.name}</p>
                </div>
              )}
              {ticket.contact && (
                <div>
                  <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide mb-1">{t("quotes.contact")}</p>
                  <Link href={`/customers/${ticket.contact.id}`} className="text-sm text-primary hover:underline font-medium">
                    {ticket.contact.firstName} {ticket.contact.lastName}
                  </Link>
                  <p className="text-xs text-muted-foreground">{ticket.contact.email}</p>
                </div>
              )}
              {ticket.account && (
                <div>
                  <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide mb-1">{t("quotes.account")}</p>
                  <Link href={`/companies/${ticket.account.id}`} className="text-sm text-primary hover:underline">
                    {ticket.account.name}
                  </Link>
                </div>
              )}
              <div className="pt-2 border-t border-border space-y-2">
                <div className="flex justify-between text-xs">
                  <span className="text-muted-foreground">{t("common.createdAt")}</span>
                  <span>{formatDate(ticket.createdAt)}</span>
                </div>
                {ticket.resolvedAt && (
                  <div className="flex justify-between text-xs">
                    <span className="text-muted-foreground">{t("tickets.stResolved")}</span>
                    <span className="text-green-600">{formatDate(ticket.resolvedAt)}</span>
                  </div>
                )}
              </div>
              <EntityCustomFieldsReadOnly
                embed
                definitions={ticket.customFieldData?.definitions ?? []}
                values={ticket.customFieldData?.values ?? {}}
              />
            </CardContent>
          </Card>

          {/* Satisfaction */}
          {ticket.satisfactionRating && (
            <Card>
              <CardHeader><CardTitle>{t("tickets.customerRating")}</CardTitle></CardHeader>
              <CardContent>
                <div className="flex gap-1">
                  {[1, 2, 3, 4, 5].map(star => (
                    <span key={star} className={`text-xl ${star <= ticket.satisfactionRating ? "text-amber-400" : "text-muted"}`}>★</span>
                  ))}
                </div>
                {ticket.satisfactionComment && (
                  <p className="text-sm text-muted-foreground mt-2 italic">
                    {`"${ticket.satisfactionComment}"`}
                  </p>
                )}
              </CardContent>
            </Card>
          )}
        </div>
      </div>

      <ConfirmDialog open={deleteOpen} onClose={() => setDeleteOpen(false)} onConfirm={handleDelete}
        isLoading={isDeleting} title={t("tickets.deleteTitle")}
        description={t("tickets.deleteDesc")}
        confirmLabel={t("common.delete")} variant="destructive" />
    </AppShell>
  );
}
