"use client";

import Layout from "@/Layout";
import { useEffect, useState, useCallback } from "react";
import { toast } from "sonner";
import {
  Headphones,
  Search,
  Plus,
  Phone,
  MessageSquare,
  Mail,
  Users,
  Clock,
  CheckCircle2,
  AlertCircle,
  ChevronDown,
  ChevronRight,
  X,
  Calendar,
  RefreshCw,
  Pencil,
  Trash2,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";

import { CallCenterAPI, type CallCenterTicket, type CallCenterFollowup } from "@/apis/CallCenterAPI";
import { CustomerAPI } from "@/apis/CustomerAPI";
import { useCompanyStore } from "@/hooks/store/useCompanyStore";
import type { CustomerRecord } from "@/types/modules/customer";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";

// ─── Helpers ────────────────────────────────────────────────────────────────

const STATUS_LABELS: Record<string, string> = {
  abierto: "Abierto",
  en_proceso: "En Proceso",
  pendiente_cliente: "Pendiente Cliente",
  resuelto: "Resuelto",
  cerrado: "Cerrado",
};

const STATUS_COLORS: Record<string, string> = {
  abierto: "bg-blue-100 text-blue-800",
  en_proceso: "bg-yellow-100 text-yellow-800",
  pendiente_cliente: "bg-orange-100 text-orange-800",
  resuelto: "bg-green-100 text-green-800",
  cerrado: "bg-slate-100 text-slate-600",
};

const TYPE_LABELS: Record<string, string> = {
  consulta: "Consulta",
  reclamo: "Reclamo",
  solicitud_pedido: "Solicitud de Pedido",
  seguimiento: "Seguimiento",
  otro: "Otro",
};

const PRIORITY_COLORS: Record<string, string> = {
  low: "bg-slate-100 text-slate-600",
  medium: "bg-blue-100 text-blue-700",
  high: "bg-orange-100 text-orange-700",
  urgent: "bg-red-100 text-red-700",
};

const PRIORITY_LABELS: Record<string, string> = {
  low: "Baja",
  medium: "Media",
  high: "Alta",
  urgent: "Urgente",
};

const CHANNEL_ICONS: Record<string, React.ReactNode> = {
  phone: <Phone className="h-3.5 w-3.5" />,
  whatsapp: <MessageSquare className="h-3.5 w-3.5" />,
  email: <Mail className="h-3.5 w-3.5" />,
  presencial: <Users className="h-3.5 w-3.5" />,
  twitter: <X className="h-3.5 w-3.5" />,
};

// ─── Main Page ───────────────────────────────────────────────────────────────

export default function CallCenterPage() {
  const { selectedCompany } = useCompanyStore();
  const selectedCompanyId = Number(selectedCompany?.id);
  const idcompany = Number.isFinite(selectedCompanyId) && selectedCompanyId > 0 ? selectedCompanyId : 1;

  // Form state
  const [formAssignedTo, setFormAssignedTo] = useState<string>("");
  const [supervisors, setSupervisors] = useState<any[]>([]);
  const [isLoadingSupervisors, setIsLoadingSupervisors] = useState(false);
  const [formSaleId, setFormSaleId] = useState<string>("none");
  const [formDueDate, setFormDueDate] = useState<string>("");
  const [showCatalogModal, setShowCatalogModal] = useState(false);
  const [catalogType, setCatalogType] = useState<"type" | "channel" | "priority" | null>(null);
  const [newCatalogValue, setNewCatalogValue] = useState("");
  const [catalogs, setCatalogs] = useState<any>(null);
  const [isLoadingCatalogs, setIsLoadingCatalogs] = useState(false);
  const [itemToDelete, setItemToDelete] = useState<number | null>(null);

  // Customer search
  const [searchInput, setSearchInput] = useState("");
  const [isSearching, setIsSearching] = useState(false);
  const [selectedCustomer, setSelectedCustomer] = useState<CustomerRecord | null>(null);
  const [customerContext, setCustomerContext] = useState<any>(null);

  // Ticket list
  const [tickets, setTickets] = useState<CallCenterTicket[]>([]);
  const [isLoadingTickets, setIsLoadingTickets] = useState(false);
  const [statusFilter, setStatusFilter] = useState<string>("all");

  // Selected ticket
  const [selectedTicket, setSelectedTicket] = useState<CallCenterTicket | null>(null);
  const [isLoadingTicket, setIsLoadingTicket] = useState(false);

  // New / edit form
  const [showForm, setShowForm] = useState(false);
  const [formSubject, setFormSubject] = useState("");
  const [formType, setFormType] = useState("consulta");
  const [formPriority, setFormPriority] = useState("medium");
  const [formChannel, setFormChannel] = useState("phone");
  const [formDescription, setFormDescription] = useState("");
  const [isSaving, setIsSaving] = useState(false);

  // Status change
  const [showStatusChange, setShowStatusChange] = useState(false);
  const [newStatus, setNewStatus] = useState("");
  const [statusComment, setStatusComment] = useState("");
  const [isChangingStatus, setIsChangingStatus] = useState(false);

  // Resolution notes
  const [resolutionNotes, setResolutionNotes] = useState("");

  // Followup form
  const [showFollowupForm, setShowFollowupForm] = useState(false);
  const [followupNotes, setFollowupNotes] = useState("");
  const [followupDate, setFollowupDate] = useState("");
  const [isSavingFollowup, setIsSavingFollowup] = useState(false);

  // ── Load tickets ──────────────────────────────────────────────────────────

  const openCatalogModal = (type: "type" | "channel" | "priority") => {
    setCatalogType(type);
    setShowCatalogModal(true);
  };

  const loadSupervisors = useCallback(async () => {
    setIsLoadingSupervisors(true);
    try {
      const data = await CallCenterAPI.getSupervisors();
      setSupervisors(data);
    } catch {
      toast.error("No se pudieron cargar los supervisores");
    } finally {
      setIsLoadingSupervisors(false);
    }
  }, []);

  const loadCatalogs = useCallback(async () => {
    setIsLoadingCatalogs(true);
    try {
      const data = await CallCenterAPI.getCatalogs();
      setCatalogs(data);
    } catch {
      toast.error("Error cargando catálogos");
    } finally {
      setIsLoadingCatalogs(false);
    }
  }, []);

  const handleSaveCatalog = async () => {
    if (!newCatalogValue.trim()) {
      toast.error("El nombre es obligatorio");
      return;
    }
    try {
      const slugValue = newCatalogValue
        .toLowerCase()
        .trim()
        .replace(/\s+/g, '_') 
        .replace(/[^\w-]+/g, ''); 
      await CallCenterAPI.createCatalog({
        type: catalogType ?? 'type',
        value: slugValue, 
        label: newCatalogValue,
      });
      toast.success("Opción agregada");
      setNewCatalogValue("");
      setShowCatalogModal(false);
      await loadCatalogs();
    } catch (error: any) {
      toast.error(error?.response?.data?.message || "Error al guardar");
    }
  };

  const handleDeleteCatalog = async (id: number) => {
    try {
      await CallCenterAPI.deleteCatalog(id);
      const updatedCatalogs = await CallCenterAPI.getCatalogs();
      setCatalogs(updatedCatalogs);
      toast.success("Opción eliminada correctamente");
    } catch (error) {
      console.error("Error al eliminar el catálogo:", error);
      toast.error("No se pudo eliminar la opción. Intente nuevamente.");
    }
  };

  const loadTickets = useCallback(async () => {
    if (!selectedCustomer) return;
    setIsLoadingTickets(true);
    try {
      const params: any = {
        idcompany,
        idcustomer: selectedCustomer.id,
        per_page: 50,
      };
      if (statusFilter !== "all") params.status = statusFilter;
      const { tickets: data } = await CallCenterAPI.getAll(params);
      setTickets(data);
    } catch {
      toast.error("No se pudieron cargar los tickets");
    } finally {
      setIsLoadingTickets(false);
    }
  }, [selectedCustomer, idcompany, statusFilter]);

  useEffect(() => {
    loadTickets();
  }, [loadTickets]);

  useEffect(() => {
    if (showForm) {
      loadSupervisors();
    }
  }, [showForm]);

  useEffect(() => {
    if (showForm) {
      loadCatalogs();
    }
  }, [showForm]);

  // ── Customer search ───────────────────────────────────────────────────────

  const handleSearch = async (e: React.FormEvent) => {
    e.preventDefault();
    const term = searchInput.trim();
    if (!term) return;

    setIsSearching(true);
    setSelectedCustomer(null);
    setCustomerContext(null);
    setTickets([]);
    setSelectedTicket(null);

    try {
      const result = await CustomerAPI.findForComplaintsContext(idcompany, term);
      if (result.status === "not_found" || !result.customer) {
        toast.error("No se encontró ningún cliente");
        return;
      }
      const customer = result.customer;
      setSelectedCustomer(customer);

      // Load context in background
      const ctx = await CallCenterAPI.getCustomerContext(customer.id, idcompany);
      setCustomerContext(ctx);
    } catch {
      toast.error("Error al buscar el cliente");
    } finally {
      setIsSearching(false);
    }
  };

  // ── Load ticket detail ────────────────────────────────────────────────────

  const handleSelectTicket = async (ticket: CallCenterTicket) => {
    setIsLoadingTicket(true);
    setShowForm(false);
    try {
      const full = await CallCenterAPI.getById(ticket.id);
      setSelectedTicket(full);
      setResolutionNotes(full.resolution_notes ?? "");
    } catch {
      toast.error("No se pudo cargar el ticket");
    } finally {
      setIsLoadingTicket(false);
    }
  };

  // ── Create ticket ─────────────────────────────────────────────────────────

  const handleCreateTicket = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedCustomer) {
      toast.error("Seleccione un cliente primero");
      return;
    }
    if (!formSubject.trim()) {
      toast.error("El asunto es obligatorio");
      return;
    }

    setIsSaving(true);
    try {
      const created = await CallCenterAPI.create({
        idcompany,
        idcustomer: selectedCustomer.id,
        type: formType,
        priority: formPriority,
        channel: formChannel,
        subject: formSubject,
        description: formDescription || undefined,
        assigned_to: formAssignedTo ? Number(formAssignedTo) : undefined,
        idsale: formSaleId && formSaleId !== "none" ? Number(formSaleId) : null,
        due_date: formDueDate || null,
      });
      toast.success(`Ticket ${created.ticket_number} creado`);
      setShowForm(false);
      setFormSubject("");
      setFormDescription("");
      setFormAssignedTo("");
      setFormSaleId("");
      setFormDueDate("");
      await loadTickets();
      const full = await CallCenterAPI.getById(created.id);
      setSelectedTicket(full);
    } catch {
      toast.error("Error al crear el ticket");
    } finally {
      setIsSaving(false);
    }
  };

  // ── Change status ─────────────────────────────────────────────────────────

  const handleChangeStatus = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedTicket || !newStatus) return;

    setIsChangingStatus(true);
    try {
      const updated = await CallCenterAPI.changeStatus(selectedTicket.id, {
        status: newStatus,
        comment: statusComment || undefined,
      });
      toast.success("Estado actualizado");
      setSelectedTicket(updated);
      setShowStatusChange(false);
      setStatusComment("");
      await loadTickets();
    } catch {
      toast.error("Error al cambiar estado");
    } finally {
      setIsChangingStatus(false);
    }
  };

  // ── Save resolution notes ─────────────────────────────────────────────────

  const handleSaveNotes = async () => {
    if (!selectedTicket) return;
    try {
      const updated = await CallCenterAPI.update(selectedTicket.id, {
        resolution_notes: resolutionNotes,
      });
      setSelectedTicket(updated);
      toast.success("Notas guardadas");
    } catch {
      toast.error("Error al guardar notas");
    }
  };

  // ── Create followup ───────────────────────────────────────────────────────

  const handleCreateFollowup = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedTicket || !followupNotes.trim() || !followupDate) return;

    setIsSavingFollowup(true);
    try {
      await CallCenterAPI.createFollowup(selectedTicket.id, {
        idcompany,
        notes: followupNotes,
        scheduled_at: followupDate,
      });
      toast.success("Seguimiento agendado");
      setShowFollowupForm(false);
      setFollowupNotes("");
      setFollowupDate("");
      const updated = await CallCenterAPI.getById(selectedTicket.id);
      setSelectedTicket(updated);
    } catch {
      toast.error("Error al agendar seguimiento");
    } finally {
      setIsSavingFollowup(false);
    }
  };

  // ── Complete followup ─────────────────────────────────────────────────────

  const handleCompleteFollowup = async (followup: CallCenterFollowup) => {
    try {
      await CallCenterAPI.completeFollowup(followup.id);
      toast.success("Seguimiento marcado como completado");
      if (selectedTicket) {
        const updated = await CallCenterAPI.getById(selectedTicket.id);
        setSelectedTicket(updated);
      }
    } catch {
      toast.error("Error al completar seguimiento");
    }
  };

  // ─── Render ───────────────────────────────────────────────────────────────

  return (
    <Layout currentPageName="Call Center">
      <div className="min-h-screen bg-slate-50/80 p-4 lg:p-6 space-y-5">

        {/* Header */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-blue-600 text-white shadow-sm">
              <Headphones className="h-5 w-5" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-slate-900">Call Center</h1>
              <p className="text-xs text-slate-500">Gestión de tickets de atención</p>
            </div>
          </div>
          {selectedCustomer && (
            <Button
              size="sm"
              className="gap-2"
              onClick={() => { setShowForm(true); setSelectedTicket(null); }}
            >
              <Plus className="h-4 w-4" /> Nuevo Ticket
            </Button>
          )}
        </div>

        {/* Search */}
        <Card>
          <CardContent className="pt-4 pb-4">
            <form onSubmit={handleSearch} className="flex gap-2">
              <Input
                placeholder="Buscar cliente por nombre, teléfono o RUT..."
                value={searchInput}
                onChange={(e) => setSearchInput(e.target.value)}
                className="flex-1"
              />
              <Button type="submit" disabled={isSearching} className="gap-2">
                {isSearching ? <RefreshCw className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
                Buscar
              </Button>
            </form>
          </CardContent>
        </Card>

        {!selectedCustomer ? (
          <div className="flex flex-col items-center justify-center py-20 text-slate-400 gap-3">
            <Headphones className="h-12 w-12 opacity-30" />
            <p className="text-sm">Busca un cliente para comenzar la atención</p>
          </div>
        ) : (
          <div className="grid grid-cols-12 gap-5">

            {/* LEFT: Customer + Context */}
            <div className="col-span-12 lg:col-span-4 space-y-4">
              {/* Customer card */}
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-semibold text-slate-700">Cliente</CardTitle>
                </CardHeader>
                <CardContent className="space-y-1.5">
                  <p className="font-semibold text-slate-900">{selectedCustomer.name}</p>
                  {selectedCustomer.phone && (
                    <p className="text-xs text-slate-500 flex items-center gap-1">
                      <Phone className="h-3 w-3" />{selectedCustomer.phone}
                    </p>
                  )}
                  {selectedCustomer.email && (
                    <p className="text-xs text-slate-500 flex items-center gap-1">
                      <Mail className="h-3 w-3" />{selectedCustomer.email}
                    </p>
                  )}
                  {selectedCustomer.tax_id && (
                    <p className="text-xs text-slate-500">RUT: {selectedCustomer.tax_id}</p>
                  )}
                  {selectedCustomer.accumulated_points !== undefined && (
                    <p className="text-xs text-blue-700 font-medium">
                      {selectedCustomer.accumulated_points} puntos acumulados
                    </p>
                  )}
                </CardContent>
              </Card>

              {/* Recent sales */}
              {customerContext?.recent_sales?.length > 0 && (
                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm font-semibold text-slate-700">Últimas Ventas</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    {customerContext.recent_sales.map((sale: any) => (
                      <div key={sale.id} className="flex justify-between text-xs">
                        <span className="text-slate-600">{sale.sale_number}</span>
                        <span className="font-medium">{sale.total?.toLocaleString("es-CL", { style: "currency", currency: "CLP" })}</span>
                      </div>
                    ))}
                  </CardContent>
                </Card>
              )}

              {/* Open tickets */}
              {customerContext?.open_tickets?.length > 0 && (
                <Card className="border-orange-200">
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm font-semibold text-orange-700 flex items-center gap-1">
                      <AlertCircle className="h-4 w-4" />
                      Tickets Abiertos ({customerContext.open_tickets.length})
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-2">
                    {customerContext.open_tickets.map((t: any) => (
                      <div key={t.id} className="text-xs space-y-0.5">
                        <p className="font-medium text-slate-800">{t.ticket_number}: {t.subject}</p>
                        <span className={`inline-block px-1.5 py-0.5 rounded text-xs ${STATUS_COLORS[t.status]}`}>
                          {STATUS_LABELS[t.status]}
                        </span>
                      </div>
                    ))}
                  </CardContent>
                </Card>
              )}

              {/* Ticket list */}
              <Card>
                <CardHeader className="pb-2">
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-sm font-semibold text-slate-700">Historial de Tickets</CardTitle>
                    <Select value={statusFilter} onValueChange={setStatusFilter}>
                      <SelectTrigger className="h-7 text-xs w-36">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">Todos</SelectItem>
                        <SelectItem value="abierto">Abiertos</SelectItem>
                        <SelectItem value="en_proceso">En Proceso</SelectItem>
                        <SelectItem value="resuelto">Resueltos</SelectItem>
                        <SelectItem value="cerrado">Cerrados</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </CardHeader>
                <CardContent className="space-y-2 max-h-80 overflow-y-auto">
                  {isLoadingTickets ? (
                    <p className="text-xs text-slate-400 text-center py-4">Cargando...</p>
                  ) : tickets.length === 0 ? (
                    <p className="text-xs text-slate-400 text-center py-4">Sin tickets</p>
                  ) : (
                    tickets.map((t) => (
                      <button
                        key={t.id}
                        type="button"
                        onClick={() => handleSelectTicket(t)}
                        className={`w-full text-left rounded-lg border p-2.5 transition-all hover:border-blue-300 hover:bg-blue-50 ${
                          selectedTicket?.id === t.id ? "border-blue-400 bg-blue-50" : "border-slate-200 bg-white"
                        }`}
                      >
                        <div className="flex items-start justify-between gap-1">
                          <p className="text-xs font-medium text-slate-800 leading-snug">{t.subject}</p>
                          <span className={`shrink-0 inline-block px-1.5 py-0.5 rounded text-[10px] font-medium ${STATUS_COLORS[t.status]}`}>
                            {STATUS_LABELS[t.status]}
                          </span>
                        </div>
                        <div className="flex items-center gap-2 mt-1">
                          <span className="text-[10px] text-slate-400">{t.ticket_number}</span>
                          <span className={`inline-block px-1.5 py-0.5 rounded text-[10px] ${PRIORITY_COLORS[t.priority]}`}>
                            {PRIORITY_LABELS[t.priority]}
                          </span>
                          <span className="text-slate-400">{CHANNEL_ICONS[t.channel]}</span>
                        </div>
                      </button>
                    ))
                  )}
                </CardContent>
              </Card>
            </div>

            {/* RIGHT: Form / Ticket detail */}
            <div className="col-span-12 lg:col-span-8 space-y-4">

              {/* New Ticket Form */}
              {showForm && (
                <Card>
                  <CardHeader className="pb-3">
                    <div className="flex items-center justify-between">
                      <CardTitle className="text-base">Nuevo Ticket</CardTitle>
                      <Button size="icon" variant="ghost" onClick={() => setShowForm(false)}>
                        <X className="h-4 w-4" />
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <form onSubmit={handleCreateTicket} className="space-y-4">
                      <div className="grid grid-cols-2 gap-3">
                        <div className="space-y-1">
                          <div className="flex items-center justify-between">
                            <Label className="text-xs">Tipo de Atención *</Label>
                            <Button
                              type="button"
                              variant="ghost"
                              size="icon"
                              className="h-6 w-6"
                              onClick={() => openCatalogModal("type")}
                            >
                              <Pencil className="h-3 w-3" />
                            </Button>
                          </div>

                          <Select value={formType} onValueChange={setFormType}>
                            <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                            <SelectContent>
                              {catalogs?.type?.map((t: any) => (
                                <SelectItem key={t.value} value={t.value}>
                                  {t.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="space-y-1">
                          <div className="flex items-center justify-between">
                            <Label className="text-xs">Canal</Label>
                            <Button
                              type="button"
                              variant="ghost"
                              size="icon"
                              className="h-6 w-6"
                              onClick={() => openCatalogModal("channel")}
                            >
                              <Pencil className="h-3 w-3" />
                            </Button>
                          </div>

                          <Select value={formChannel} onValueChange={setFormChannel}>
                            <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                            <SelectContent>
                              {catalogs?.channel?.map((c: any) => (
                                <SelectItem key={c.value} value={c.value}>
                                  {c.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="space-y-1">
                          <div className="flex items-center justify-between">
                            <Label className="text-xs">Prioridad</Label>
                            <Button
                              type="button"
                              variant="ghost"
                              size="icon"
                              className="h-6 w-6"
                              onClick={() => openCatalogModal("priority")}
                            >
                              <Pencil className="h-3 w-3" />
                            </Button>
                          </div>

                          <Select value={formPriority} onValueChange={setFormPriority}>
                            <SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
                            <SelectContent>
                              {catalogs?.priority?.map((p: any) => (
                                <SelectItem key={p.value} value={p.value}>
                                  {p.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs">Seleccionar Pedido</Label>
                          <Select value={formSaleId} onValueChange={setFormSaleId}>
                            <SelectTrigger className="h-9">
                              <SelectValue placeholder="Seleccionar pedido (opcional)" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="none">Sin pedido</SelectItem>
                              {customerContext?.recent_sales?.map((sale: any) => (
                                <SelectItem key={sale.id} value={String(sale.id)}>
                                  {sale.sale_number} — {new Date(sale.sale_date).toLocaleDateString("es-CL", {
                                    day: "2-digit",
                                    month: "short",
                                    year: "numeric",
                                  })}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs">Asignar Responsable</Label>
                          <Select value={formAssignedTo} onValueChange={setFormAssignedTo}>
                            <SelectTrigger className="h-9">
                              <SelectValue placeholder="Seleccionar responsable" />
                            </SelectTrigger>
                            <SelectContent>
                              {isLoadingSupervisors ? (
                                <SelectItem value="loading" disabled>Cargando...</SelectItem>
                              ) : supervisors.length === 0 ? (
                                <SelectItem value="empty" disabled>Sin supervisores</SelectItem>
                              ) : (
                                supervisors.map((u) => (
                                  <SelectItem key={u.id} value={String(u.id)}>
                                    {u.name} — {u.email}
                                  </SelectItem>
                                ))
                              )}
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs">Asignar Fecha de Resolución</Label>
                          <Input
                            type="datetime-local"
                            value={formDueDate}
                            onChange={(e) => setFormDueDate(e.target.value)}
                            className="h-9"
                          />
                        </div>
                      </div>
                      <div className="space-y-1">
                        <Label className="text-xs">Asunto *</Label>
                        <Input
                          value={formSubject}
                          onChange={(e) => setFormSubject(e.target.value)}
                          placeholder="Ej: Consulta sobre pedido #001234"
                          className="h-9"
                        />
                      </div>
                      <div className="space-y-1">
                        <Label className="text-xs">Descripción</Label>
                        <Textarea
                          value={formDescription}
                          onChange={(e) => setFormDescription(e.target.value)}
                          rows={3}
                          placeholder="Detalle de la atención..."
                        />
                      </div>
                      <div className="flex justify-end gap-2">
                        <Button type="button" variant="outline" size="sm" onClick={() => setShowForm(false)}>
                          Cancelar
                        </Button>
                        <Button type="submit" size="sm" disabled={isSaving}>
                          {isSaving ? "Guardando..." : "Crear Ticket"}
                        </Button>
                      </div>
                    </form>
                  </CardContent>
                </Card>
              )}

              {/* Ticket detail */}
              {!showForm && selectedTicket && (
                <>
                  <Card>
                    <CardHeader className="pb-3">
                      <div className="flex items-start justify-between">
                        <div>
                          <p className="text-xs text-slate-500">{selectedTicket.ticket_number} · {selectedTicket.opened_at}</p>
                          <h2 className="text-base font-semibold text-slate-900 mt-0.5">{selectedTicket.subject}</h2>
                        </div>
                        <div className="flex items-center gap-2 shrink-0">
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${STATUS_COLORS[selectedTicket.status]}`}>
                            {STATUS_LABELS[selectedTicket.status]}
                          </span>
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${PRIORITY_COLORS[selectedTicket.priority]}`}>
                            {PRIORITY_LABELS[selectedTicket.priority]}
                          </span>
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex gap-4 text-xs text-slate-500">
                        <span className="flex items-center gap-1">{CHANNEL_ICONS[selectedTicket.channel]} {selectedTicket.channel}</span>
                        <span>{selectedTicket.type_label || TYPE_LABELS[selectedTicket.type] || selectedTicket.type}</span>
                        {selectedTicket.assigned_to && (
                          <span>Asignado: {selectedTicket.assigned_to?.user_name ?? selectedTicket.assigned_to?.email}</span>
                        )}
                      </div>

                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 bg-slate-50/50 p-2 rounded-lg border border-dashed border-slate-200">
                        <div className="flex flex-col gap-0.5">
                          <span className="text-[10px] font-bold text-slate-400 uppercase">Pedido Relacionado</span>
                          {selectedTicket.sale ? (
                            <span className="text-xs font-semibold text-blue-600">
                              #{selectedTicket.sale.sale_number} — {selectedTicket.sale.sale_date ? 
                                new Date(selectedTicket.sale.sale_date).toLocaleDateString("es-CL", {
                                  day: "2-digit",
                                  month: "short",
                                  year: "numeric",
                                }) : 'Sin fecha'}
                            </span>
                          ) : (
                            <span className="text-xs text-slate-400 italic">No asociado</span>
                          )}
                        </div>

                        <div className="flex flex-col gap-0.5">
                          <span className="text-[10px] font-bold text-slate-400 uppercase">Fecha de Resolución</span>
                          <span className={`text-xs font-medium ${selectedTicket.due_date ? 'text-slate-700' : 'text-slate-400 italic'}`}>
                            {selectedTicket.due_date || 'Sin fecha límite'}
                          </span>
                        </div>
                      </div>

                      {selectedTicket.description && (
                        <div>
                          <p className="text-xs font-medium text-slate-600 mb-1">Descripción</p>
                          <p className="text-sm text-slate-700 bg-slate-50 rounded-lg p-3">{selectedTicket.description}</p>
                        </div>
                      )}

                      <Separator />

                      {/* Action buttons */}
                      <div className="flex flex-wrap gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          className="gap-1 text-xs"
                          disabled={selectedTicket.status === 'cerrado'}
                          onClick={() => { setNewStatus(selectedTicket.status); setShowStatusChange(true); }}
                        >
                          <RefreshCw className="h-3.5 w-3.5" /> Cambiar Estado
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          className="gap-1 text-xs"
                          onClick={() => setShowFollowupForm(!showFollowupForm)}
                        >
                          <Calendar className="h-3.5 w-3.5" /> Agendar Seguimiento
                        </Button>
                        {selectedTicket.status !== 'resuelto' && selectedTicket.status !== 'cerrado' && (
                          <Button
                            size="sm"
                            className="gap-1 text-xs bg-green-600 hover:bg-green-700"
                            onClick={() => {
                              setNewStatus("resuelto");
                              setShowStatusChange(true);
                            }}
                          >
                            <CheckCircle2 className="h-3.5 w-3.5" /> Resolver
                          </Button>
                        )}
                      </div>

                      {/* Status change form */}
                      {showStatusChange && (
                        <form onSubmit={handleChangeStatus} className="border rounded-lg p-3 space-y-3 bg-slate-50">
                          <p className="text-xs font-semibold text-slate-700">Cambiar Estado</p>
                          <Select value={newStatus} onValueChange={setNewStatus}>
                            <SelectTrigger className="h-8 text-xs"><SelectValue /></SelectTrigger>
                            <SelectContent>
                              {Object.entries(STATUS_LABELS).map(([v, l]) => (
                                <SelectItem key={v} value={v} className="text-xs">{l}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <Input
                            value={statusComment}
                            onChange={(e) => setStatusComment(e.target.value)}
                            placeholder="Comentario (opcional)"
                            className="h-8 text-xs"
                          />
                          <div className="flex gap-2 justify-end">
                            <Button type="button" size="sm" variant="ghost" className="text-xs h-7" onClick={() => setShowStatusChange(false)}>
                              Cancelar
                            </Button>
                            <Button type="submit" size="sm" className="text-xs h-7" disabled={isChangingStatus}>
                              {isChangingStatus ? "..." : "Confirmar"}
                            </Button>
                          </div>
                        </form>
                      )}

                      {/* Followup form */}
                      {showFollowupForm && (
                        <form onSubmit={handleCreateFollowup} className="border rounded-lg p-3 space-y-3 bg-slate-50">
                          <p className="text-xs font-semibold text-slate-700">Nuevo Seguimiento</p>
                          <Textarea
                            value={followupNotes}
                            onChange={(e) => setFollowupNotes(e.target.value)}
                            placeholder="Descripción del seguimiento..."
                            rows={2}
                            className="text-xs"
                          />
                          <Input
                            type="datetime-local"
                            value={followupDate}
                            onChange={(e) => setFollowupDate(e.target.value)}
                            className="h-8 text-xs"
                          />
                          <div className="flex gap-2 justify-end">
                            <Button type="button" size="sm" variant="ghost" className="text-xs h-7" onClick={() => setShowFollowupForm(false)}>
                              Cancelar
                            </Button>
                            <Button type="submit" size="sm" className="text-xs h-7" disabled={isSavingFollowup}>
                              {isSavingFollowup ? "..." : "Agendar"}
                            </Button>
                          </div>
                        </form>
                      )}
                    </CardContent>
                  </Card>

                  {/* Resolution notes */}
                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-semibold text-slate-700">Notas de Resolución</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      <Textarea
                        value={resolutionNotes}
                        onChange={(e) => setResolutionNotes(e.target.value)}
                        rows={3}
                        placeholder="Escribe aquí la solución o notas del caso..."
                      />
                      <div className="flex justify-end">
                        <Button size="sm" variant="outline" className="text-xs" onClick={handleSaveNotes}>
                          Guardar Notas
                        </Button>
                      </div>
                    </CardContent>
                  </Card>

                  {/* History timeline */}
                  {selectedTicket.histories && selectedTicket.histories.length > 0 && (
                    <Card>
                      <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-semibold text-slate-700 flex items-center gap-1">
                          <Clock className="h-4 w-4" /> Historial de Estados
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-3">
                          {selectedTicket.histories.map((h: any) => (
                            <div key={h.id} className="flex gap-3">
                              <div className="flex flex-col items-center">
                                <div className="h-2 w-2 rounded-full bg-blue-400 mt-1.5" />
                                <div className="w-px flex-1 bg-slate-200 mt-1" />
                              </div>
                              <div className="pb-3">
                                <div className="flex items-center gap-2 text-xs">
                                  {h.old_status && (
                                    <>
                                      <span className={`px-1.5 py-0.5 rounded ${STATUS_COLORS[h.old_status]}`}>
                                        {STATUS_LABELS[h.old_status]}
                                      </span>
                                      <ChevronRight className="h-3 w-3 text-slate-400" />
                                    </>
                                  )}
                                  <span className={`px-1.5 py-0.5 rounded ${STATUS_COLORS[h.new_status]}`}>
                                    {STATUS_LABELS[h.new_status]}
                                  </span>
                                </div>
                                {h.comment && <p className="text-xs text-slate-500 mt-0.5">{h.comment}</p>}
                                <p className="text-[10px] text-slate-400 mt-0.5">
                                  {h.user?.user_name ?? h.changed_by?.user_name ?? h.user?.email ?? h.changed_by?.email ?? 'admin'} · {h.created_at}
                                </p>
                              </div>
                            </div>
                          ))}
                        </div>
                      </CardContent>
                    </Card>
                  )}

                  {/* Followups */}
                  {selectedTicket.followups && selectedTicket.followups.length > 0 && (
                    <Card>
                      <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-semibold text-slate-700 flex items-center gap-1">
                          <Calendar className="h-4 w-4" /> Seguimientos
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-3">
                        {selectedTicket.followups.map((f: any) => (
                          <div key={f.id} className="flex items-start justify-between border rounded-lg p-3 bg-slate-50">
                            <div className="space-y-1">
                              <p className="text-xs font-medium text-slate-700">{f.notes}</p>
                              <p className="text-[10px] text-slate-500">Programado: {f.scheduled_at}</p>
                              {f.completed_at && (
                                <p className="text-[10px] text-green-600">Completado: {f.completed_at}</p>
                              )}
                            </div>
                            <div className="flex items-center gap-2 shrink-0">
                              <span className={`px-1.5 py-0.5 rounded text-[10px] font-medium ${
                                f.status === 'completed' ? 'bg-green-100 text-green-700' :
                                f.status === 'cancelled' ? 'bg-red-100 text-red-700' :
                                'bg-yellow-100 text-yellow-700'
                              }`}>
                                {f.status === 'completed' ? 'Completado' : f.status === 'cancelled' ? 'Cancelado' : 'Pendiente'}
                              </span>
                              {f.status === 'pending' && (
                                <Button
                                  size="sm"
                                  variant="ghost"
                                  className="h-6 text-[10px] text-green-700"
                                  onClick={() => handleCompleteFollowup(f)}
                                >
                                  <CheckCircle2 className="h-3.5 w-3.5" />
                                </Button>
                              )}
                            </div>
                          </div>
                        ))}
                      </CardContent>
                    </Card>
                  )}
                </>
              )}

              {/* Empty state */}
              {!showForm && !selectedTicket && !isLoadingTicket && (
                <div className="flex flex-col items-center justify-center h-64 text-slate-400 gap-3 border-2 border-dashed rounded-xl">
                  <Headphones className="h-10 w-10 opacity-30" />
                  <p className="text-sm">Selecciona un ticket o crea uno nuevo</p>
                  <Button size="sm" variant="outline" className="gap-1" onClick={() => setShowForm(true)}>
                    <Plus className="h-4 w-4" /> Nuevo Ticket
                  </Button>
                </div>
              )}

              {isLoadingTicket && (
                <div className="flex items-center justify-center h-40">
                  <RefreshCw className="h-6 w-6 animate-spin text-blue-400" />
                </div>
              )}
            </div>
          </div>
        )}
      </div>
      {showCatalogModal && (
        <>
          <Dialog open={showCatalogModal} onOpenChange={setShowCatalogModal}>
            <DialogContent className="max-w-sm">
              <DialogHeader>
                <DialogTitle>
                  Gestionar{" "}
                  {catalogType === "type" && "Tipos"}
                  {catalogType === "channel" && "Canales"}
                  {catalogType === "priority" && "Prioridades"}
                </DialogTitle>
              </DialogHeader>

              <div className="space-y-4">
                <div className="space-y-2">
                  <Label className="text-[10px] font-bold text-slate-400 uppercase">Opciones Actuales</Label>
                  <div className="max-h-40 overflow-y-auto border rounded-md divide-y divide-slate-100 bg-slate-50/50">
                    {catalogs?.[catalogType as keyof typeof catalogs]?.map((item: any) => (
                      <div key={item.value} className="flex items-center justify-between p-2 text-sm">
                        <span className={item.is_custom ? "text-slate-700 font-medium" : "text-slate-400 italic"}>
                          {item.label}
                        </span>
                        
                        {item.is_custom ? (
                          <button 
                            onClick={() => setItemToDelete(item.id)}
                            className="text-red-400 hover:text-red-600 transition-colors p-1"
                            title="Eliminar de forma lógica"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        ) : (
                          <span className="text-[9px] bg-slate-200 text-slate-500 px-1.5 py-0.5 rounded font-bold uppercase">
                            Sistema
                          </span>
                        )}
                      </div>
                    ))}
                    
                    {catalogs?.[catalogType as keyof typeof catalogs]?.length === 0 && (
                      <div className="p-4 text-center text-xs text-slate-400"> No hay opciones personalizadas.</div>
                    )}
                  </div>
                </div>

                <hr className="border-slate-100" />

                <div className="space-y-1">
                  <Label className="text-xs">Agregar Nuevo Nombre</Label>
                  <div className="flex gap-2">
                    <Input
                      placeholder="Ej: Reclamo urgente..."
                      value={newCatalogValue}
                      onChange={(e) => setNewCatalogValue(e.target.value)}
                      onKeyDown={(e) => e.key === 'Enter' && newCatalogValue.trim() && handleSaveCatalog()}
                    />
                    <Button 
                      onClick={handleSaveCatalog} 
                      disabled={!newCatalogValue.trim()}
                      size="sm"
                    >
                      Añadir
                    </Button>
                  </div>
                </div>
              </div>
            </DialogContent>
          </Dialog>

          <AlertDialog open={!!itemToDelete} onOpenChange={() => setItemToDelete(null)}>
            {(() => {
              const ContentTag = AlertDialogContent as any;
              
              return (
                <ContentTag className="max-w-[400px]">
                  <div className="p-6 space-y-4">
                    <div className="space-y-2">
                      <h2 className="text-lg font-semibold text-slate-900">¿Eliminar esta opción?</h2>
                      <p className="text-sm text-slate-500">
                        Esta acción es reversible desde la base de datos. La opción ya no aparecerá en nuevos tickets.
                      </p>
                    </div>
                    <div className="flex justify-end gap-3 pt-4">
                      <Button 
                        variant="outline" 
                        type="button"
                        onClick={() => setItemToDelete(null)}
                      >
                        Cancelar
                      </Button>
                      <Button 
                        variant="destructive" 
                        type="button"
                        onClick={() => {
                          if (itemToDelete) {
                            handleDeleteCatalog(itemToDelete);
                            setItemToDelete(null);
                          }
                        }}
                      >
                        Confirmar Eliminación
                      </Button>
                    </div>
                  </div>
                </ContentTag>
              );
            })()}
          </AlertDialog>
        </>
      )}
    </Layout>
  );
}
