"use client";

import {
  Calendar,
  CheckCircle2,
  Clock,
  Edit,
  MapPin,
  Package,
  Trash2,
  Truck,
  User,
  Wrench,
  X,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { formatDate } from "@/lib/utils";
import { ScheduleEvent, ScheduleEventStatus, ScheduleEventType } from "@/types/schedule";

interface ScheduleDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  event: ScheduleEvent | null;
  onEdit: (event: ScheduleEvent) => void;
  onDelete: (id: string) => void;
  onComplete: (id: string) => void;
}

export function ScheduleDetailModal({
  isOpen,
  onClose,
  event,
  onEdit,
  onDelete,
  onComplete,
}: ScheduleDetailModalProps) {
  if (!isOpen || !event) return null;

  const renderTypeBadge = (type: ScheduleEventType) => {
    switch (type) {
      case "DELIVERY":
        return <Badge tone="green">Entrega / Mobilização</Badge>;
      case "RETURN":
        return <Badge tone="blue">Devolução / Coleta</Badge>;
      case "MAINTENANCE":
        return <Badge tone="blue">Manutenção Preventiva</Badge>;
      case "INSPECTION":
        return <Badge tone="blue">Vistoria Técnica</Badge>;
      default:
        return <Badge tone="blue">{type}</Badge>;
    }
  };

  const renderStatusBadge = (status: ScheduleEventStatus) => {
    switch (status) {
      case "COMPLETED":
        return <Badge tone="green">Concluído</Badge>;
      case "IN_TRANSIT":
        return <Badge tone="blue">Em Trânsito</Badge>;
      case "SCHEDULED":
        return <Badge tone="blue">Agendado</Badge>;
      case "CANCELED":
        return <Badge tone="red">Cancelado</Badge>;
      default:
        return <Badge tone="blue">{status}</Badge>;
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-xs transition-all">
      <Card className="w-full max-w-2xl max-h-[90vh] overflow-y-auto p-6 shadow-2xl">
        {/* Header */}
        <div className="flex flex-wrap items-start justify-between gap-4 border-b pb-4">
          <div className="flex items-center gap-3">
            <div className="rounded-xl border bg-muted/60 p-3">
              <Truck className="h-7 w-7 text-primary" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                {renderTypeBadge(event.type)}
                {renderStatusBadge(event.status)}
              </div>
              <h2 className="text-xl font-bold text-foreground mt-1">{event.title}</h2>
              <p className="text-xs text-muted-foreground flex items-center gap-1 mt-0.5">
                <Calendar className="h-3.5 w-3.5" />
                Data: {formatDate(event.startDate)}
              </p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Button variant="secondary" size="sm" onClick={() => onEdit(event)}>
              <Edit className="mr-1.5 h-4 w-4" /> Editar
            </Button>

            <Button
              variant="ghost"
              size="icon"
              className="text-rose-500 hover:bg-rose-500/10 hover:text-rose-600"
              onClick={() => {
                if (confirm(`Tem certeza que deseja excluir o agendamento ${event.title}?`)) {
                  onDelete(event.id);
                  onClose();
                }
              }}
            >
              <Trash2 className="h-4 w-4" />
            </Button>

            <Button variant="ghost" size="icon" onClick={onClose}>
              <X className="h-5 w-5" />
            </Button>
          </div>
        </div>

        {/* Detalhes do Cliente e Máquina */}
        <div className="mt-5 grid gap-4 sm:grid-cols-2">
          <div className="rounded-xl border bg-card p-4">
            <p className="text-xs font-semibold uppercase text-muted-foreground flex items-center gap-1.5 mb-2">
              <User className="h-4 w-4 text-blue-500" /> Cliente / Obra
            </p>
            <p className="font-bold text-foreground">
              {event.customer?.name || "Cliente não especificado"}
            </p>
            {event.customer?.phone && (
              <p className="text-xs text-muted-foreground mt-0.5">
                Contato: {event.customer.phone}
              </p>
            )}
          </div>

          <div className="rounded-xl border bg-card p-4">
            <p className="text-xs font-semibold uppercase text-muted-foreground flex items-center gap-1.5 mb-2">
              <Package className="h-4 w-4 text-purple-500" /> Equipamento
            </p>
            <p className="font-bold text-foreground">
              {event.equipment
                ? `${event.equipment.brand} ${event.equipment.model}`
                : "Máquina Industrial"}
            </p>
            {event.equipment?.code && (
              <p className="text-xs font-mono text-muted-foreground mt-0.5">
                Código: {event.equipment.code} ({event.equipment.assetTag})
              </p>
            )}
          </div>
        </div>

        {/* Localização e Responsável */}
        <div className="mt-4 grid gap-4 sm:grid-cols-2">
          <div className="rounded-xl border bg-muted/40 p-4">
            <p className="text-xs font-semibold uppercase text-muted-foreground flex items-center gap-1.5">
              <MapPin className="h-4 w-4 text-rose-500" /> Endereço da Obra
            </p>
            <p className="mt-1 text-sm font-medium text-foreground">
              {event.location || "Canteiro de Obras do Cliente"}
            </p>
          </div>

          <div className="rounded-xl border bg-muted/40 p-4">
            <p className="text-xs font-semibold uppercase text-muted-foreground flex items-center gap-1.5">
              <Truck className="h-4 w-4 text-emerald-500" /> Motorista / Técnico
            </p>
            <p className="mt-1 text-sm font-medium text-foreground">
              {event.technician || "Equipe de Despacho"}
            </p>
          </div>
        </div>

        {/* Observações */}
        {event.notes && (
          <div className="mt-4 rounded-xl border bg-blue-500/5 p-4 border-blue-500/20">
            <h3 className="text-xs font-semibold uppercase tracking-wider text-blue-600 dark:text-blue-400">
              Instruções de Transporte e Acesso
            </h3>
            <p className="mt-1 text-sm text-foreground/90">{event.notes}</p>
          </div>
        )}

        {/* Botão de Conclusão */}
        {event.status !== "COMPLETED" && (
          <div className="mt-6 rounded-xl border bg-emerald-500/10 p-4 border-emerald-500/30 flex items-center justify-between gap-4">
            <div>
              <h4 className="font-bold text-emerald-700 dark:text-emerald-300">
                Ação realizada?
              </h4>
              <p className="text-xs text-muted-foreground">
                Marque este agendamento como concluído para atualizar o histórico.
              </p>
            </div>
            <Button
              onClick={() => {
                onComplete(event.id);
                onClose();
              }}
              className="bg-emerald-600 hover:bg-emerald-700 text-white shadow-xs"
            >
              <CheckCircle2 className="mr-1.5 h-4 w-4" /> Marcar como Concluído
            </Button>
          </div>
        )}

        <div className="mt-6 flex justify-end border-t pt-4">
          <Button variant="secondary" onClick={onClose}>
            Fechar
          </Button>
        </div>
      </Card>
    </div>
  );
}
