"use client";

import type { ChangeEvent } from "react";
import { Pencil, User } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { ComplaintTimeline } from "./ComplaintTimeline";

import type {
  ComplaintCatalogRecord,
  ComplaintRecord,
} from "@/types/modules/complaint";
import type { CustomerRecord } from "@/types/modules/customer";

type TicketFormProps = {
  customer?: CustomerRecord | null;
  serviceContext?: any;
  selectedComplaint?: ComplaintRecord | null;
  types: ComplaintCatalogRecord[];
  statuses: ComplaintCatalogRecord[];
  title: string;
  description: string;
  typeId: string;
  statusId: string;
  onTitleChange: (v: string) => void;
  onDescriptionChange: (v: string) => void;
  onTypeChange: (v: string) => void;
  onStatusChange: (v: string) => void;
  // Estados de carga
  catalogsLoading: boolean;
  isLoading: boolean;
  onSave: () => Promise<void>;
};

export function TicketForm({
  customer,
  serviceContext,
  selectedComplaint,
  types,
  statuses,
  title,
  description,
  typeId,
  statusId,
  onTitleChange,
  onDescriptionChange,
  onTypeChange,
  onStatusChange,
  catalogsLoading,
  isLoading,
  onSave,
}: TicketFormProps) {
  
  const displayOrderNumber = () => {
      // Caso 1: Edición de un reclamo existente
      if (selectedComplaint?.idproduction_order) {
        return `OS-${selectedComplaint.idproduction_order}`;
      }

      // Caso 2: Nuevo reclamo con pedido automático (el ganador del backend)
      const lastTx = serviceContext?.last_transaction;

      if (lastTx && lastTx.invoice_number) {
        return lastTx.invoice_number;
      }

      // Caso 3: Fallback si no tiene pedidos registrados
      return "Sin pedido asociado";
  };

  const displayComplaintNumber = (): string => {
    if (selectedComplaint?.complaint_number) {
      return String(selectedComplaint.complaint_number);
    }

    if (selectedComplaint?.id) {
      return `#${String(selectedComplaint.id).padStart(8, '0')}`;
    }

    return "#00000000";
  };

  console.log("Reclamo Seleccionado:", selectedComplaint);
  console.log("Historiales:", selectedComplaint?.histories);
  return (
    <Card className="rounded-xl border-slate-200/80 bg-white shadow-sm">
      <CardHeader className="flex flex-row items-start justify-between space-y-0">
        <div>
          <CardTitle className="text-lg font-semibold">Ticket de Reclamo</CardTitle>
          <CardDescription>
            {selectedComplaint?.id ? "Edición de ticket" : "Nuevo ticket"}
          </CardDescription>
        </div>
        <div className="flex gap-1">
          <Button size="icon" variant="ghost" type="button" className="rounded-lg">
            <Pencil className="h-4 w-4 text-slate-600" />
          </Button>
          <Button size="icon" variant="ghost" type="button" className="rounded-lg">
            <User className="h-4 w-4 text-slate-600" />
          </Button>
        </div>
      </CardHeader>
      
      <CardContent className="space-y-6">
        <div className="flex flex-wrap gap-4 text-sm text-blue-700">
          <span>
            <span>
              <span className="text-slate-500">ID Reclamo:</span>{" "}
              <span className="font-medium">{displayComplaintNumber()}</span>
            </span>
          </span>
          <span>
            <span className="text-slate-500">RUT:</span>{" "}
            <span className="font-medium">{customer?.tax_id || "—"}</span>
          </span>
        </div>

        {isLoading ? (
          <div className="space-y-3">
            <Skeleton className="h-4 w-full" />
            <Skeleton className="h-4 w-3/4" />
          </div>
        ) : (
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <p className="text-xs font-medium uppercase text-slate-500">Cliente</p>
              <p className="text-sm font-semibold text-slate-900">
                {customer?.name || "Seleccione un cliente"}
              </p>
            </div>
            <div>
              <p className="text-xs font-medium uppercase text-slate-500">Pedido asociado</p>
              <p className="text-sm font-semibold text-blue-600">
                {displayOrderNumber()}
              </p>
            </div>
          </div>
        )}

        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="ticket-title">Título</Label>
            <Input
              id="ticket-title"
              className="rounded-xl shadow-sm"
              placeholder="Ej: Retraso en entrega de pedido..."
              value={title}
              onChange={(e: ChangeEvent<HTMLInputElement>) => onTitleChange(e.target.value)}
              disabled={isLoading}
            />
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label>Tipo de Reclamo</Label>
              {catalogsLoading ? (
                <Skeleton className="h-10 w-full rounded-md" />
              ) : (
                <Select value={typeId} onValueChange={onTypeChange}>
                  <SelectTrigger className="rounded-xl shadow-sm">
                    <SelectValue placeholder="Selecciona tipo" />
                  </SelectTrigger>
                  <SelectContent>
                    {(Array.isArray(types) ? types : []).map((t) => (
                      <SelectItem key={t.id} value={t.id.toString()}>
                        {t.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
            </div>

            <div className="space-y-2">
              <Label>Estado del Reclamo</Label>
              {catalogsLoading ? (
                <Skeleton className="h-10 w-full rounded-md" />
              ) : (
                <Select value={statusId} onValueChange={onStatusChange}>
                  <SelectTrigger className="rounded-xl shadow-sm">
                    <SelectValue placeholder="Selecciona estado" />
                  </SelectTrigger>
                  <SelectContent>
                    {(Array.isArray(statuses) ? statuses : []).map((s) => (
                      <SelectItem key={s.id} value={s.id.toString()}>
                        {s.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="ticket-desc">Descripción del Reclamo</Label>
            <Textarea
              id="ticket-desc"
              className="min-h-[120px] rounded-xl shadow-sm"
              placeholder="Describe el motivo del reclamo..."
              value={description}
              onChange={(e: ChangeEvent<HTMLTextAreaElement>) =>
                onDescriptionChange(e.target.value)
              }
              disabled={isLoading}
            />
          </div>
        </div>

        {/* Línea de tiempo / Historial del reclamo */}
        {selectedComplaint && (
          <ComplaintTimeline 
            histories={selectedComplaint.histories || []} 
            showContextSkeleton={isLoading}
          />
        )}

        <div className="flex flex-wrap gap-3">
          <Button
            className="rounded-xl bg-blue-600 hover:bg-blue-700 shadow-sm px-8"
            type="button"
            onClick={onSave}
            disabled={isLoading || !customer}
          >
            {selectedComplaint?.id ? "Guardar cambios" : "Crear reclamo"}
          </Button>
          <Button
            className="rounded-xl shadow-sm"
            type="button"
            variant="outline"
            onClick={() => toast.info("Funcionalidad próximamente.")}
          >
            Asociar a otro Pedido
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
