"use client";

import { useEffect, useState } from "react";
import { useQuery } from "convex/react";
import { formatDistanceToNow } from "date-fns";
import { ptBR } from "date-fns/locale";
import { api } from "@/convex/_generated/api";
import { DEFAULT_TENANT_ID } from "@/lib/constants";
import { mapTicketWithDetailsFromServer } from "@/lib/mappers/ticket";
import type { Id } from "@/convex/_generated/dataModel";
import type { TicketWithDetails } from "@/lib/schemas/ticket";
import { Card, CardContent } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { TicketComments } from "@/components/tickets/ticket-comments.rich";
import { TicketDetailsPanel } from "@/components/tickets/ticket-details-panel";
import { TicketSummaryHeader } from "@/components/tickets/ticket-summary-header";
import { TicketTimeline } from "@/components/tickets/ticket-timeline";
import { TicketCsatCard } from "@/components/tickets/ticket-csat-card";
import { TicketChatHistory } from "@/components/tickets/ticket-chat-history";
import { TicketChecklistCard } from "@/components/tickets/ticket-checklist-card";
import { useAuth } from "@/lib/auth-client";

export function TicketDetailView({ id }: { id: string }) {
  const { convexUserId } = useAuth();
  const canLoadTicket = Boolean(convexUserId);
  const t = useQuery(
    api.tickets.getById,
    canLoadTicket
      ? {
          tenantId: DEFAULT_TENANT_ID,
          id: id as Id<"tickets">,
          viewerId: convexUserId as Id<"users">,
        }
      : "skip"
  );
  const isLoading = !convexUserId || t === undefined;

  if (isLoading) {
    return (
      <div className="flex flex-col gap-6 px-4 lg:px-6">
        <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
          <CardContent className="space-y-3 p-6">
            <div className="flex items-center gap-2"><Skeleton className="h-5 w-24" /><Skeleton className="h-5 w-20" /></div>
            <Skeleton className="h-7 w-2/3" />
            <Skeleton className="h-4 w-1/2" />
          </CardContent>
        </Card>
        <div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
          <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
            <CardContent className="space-y-4 p-6">
              {Array.from({ length: 3 }).map((_, i) => (
                <div key={i} className="space-y-2">
                  <div className="flex items-center gap-2"><Skeleton className="h-4 w-28" /><Skeleton className="h-3 w-24" /></div>
                  <Skeleton className="h-16 w-full" />
                </div>
              ))}
            </CardContent>
          </Card>
          <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
            <CardContent className="space-y-3 p-6">
              {Array.from({ length: 5 }).map((_, i) => (<Skeleton key={i} className="h-3 w-full" />))}
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  if (!t) {
    return (
      <div className="flex flex-col gap-6 px-4 lg:px-6">
        <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
          <CardContent className="space-y-3 p-6">
            <p className="text-base font-semibold text-neutral-900">Ticket não encontrado</p>
            <p className="text-sm text-neutral-600">O ticket solicitado não existe ou você não tem permissão para visualizá-lo.</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  const ticket = mapTicketWithDetailsFromServer(t as unknown) as TicketWithDetails | null;

  if (!ticket) {
    return (
      <div className="flex flex-col gap-6 px-4 lg:px-6">
        <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
          <CardContent className="space-y-3 p-6">
            <p className="text-base font-semibold text-neutral-900">Ticket não encontrado</p>
            <p className="text-sm text-neutral-600">O ticket solicitado não existe ou você não tem permissão para visualizá-lo.</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  const handlePrioritizeClick = () => {
    if (typeof window === "undefined") return;
    const anchor = document.getElementById("ticket-summary-header");
    anchor?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <div className="flex flex-col gap-6 px-4 lg:px-6">
      <TicketSlaBanner ticket={ticket} onPrioritize={handlePrioritizeClick} />
      <TicketSummaryHeader ticket={ticket} />
      <TicketCsatCard ticket={ticket} />
      <div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
        <div className="space-y-6">
          <TicketChecklistCard ticket={ticket} />
          <TicketComments ticket={ticket} />
          <TicketTimeline ticket={ticket} />
          <TicketChatHistory ticketId={id} />
        </div>
        <TicketDetailsPanel ticket={ticket} />
      </div>
    </div>
  );
}

const SLA_WARNING_THRESHOLD_MS = 1000 * 60 * 60 * 4;

function TicketSlaBanner({ ticket, onPrioritize }: { ticket: TicketWithDetails; onPrioritize: () => void }) {
  const [now, setNow] = useState(Date.now());

  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 60000);
    return () => clearInterval(id);
  }, []);

  const dueAtDate = ticket.dueAt ? new Date(ticket.dueAt) : null;
  if (!dueAtDate || ticket.status === "RESOLVED") {
    return null;
  }

  const diff = dueAtDate.getTime() - now;
  const isOverdue = diff <= 0;
  const isNearThreshold = diff > 0 && diff <= SLA_WARNING_THRESHOLD_MS;

  if (!isOverdue && !isNearThreshold) {
    return null;
  }

  const label = isOverdue
    ? `SLA vencido ${formatDistanceToNow(dueAtDate, { addSuffix: true, locale: ptBR })}`
    : `Faltam ${formatDistanceToNow(dueAtDate, { locale: ptBR })} para o SLA`;

  const containerClasses = isOverdue
    ? "border-rose-200 bg-rose-50 text-rose-900"
    : "border-amber-200 bg-amber-50 text-amber-900";

  const buttonVariant = isOverdue ? "destructive" : "outline";

  return (
    <div
      className={`flex flex-col gap-3 rounded-2xl border px-4 py-4 shadow-sm sm:flex-row sm:items-center sm:justify-between ${containerClasses}`}
    >
      <div>
        <p className="text-sm font-semibold">{isOverdue ? "SLA em atraso" : "SLA em risco"}</p>
        <p className="text-sm">{label}</p>
      </div>
      <Button variant={buttonVariant as "destructive" | "outline"} onClick={onPrioritize} className="w-full sm:w-auto">
        Priorizar atendimento
      </Button>
    </div>
  );
}
