"use client";

import {
  Calendar as CalendarIcon,
  CheckCircle2,
  ChevronLeft,
  ChevronRight,
  Clock,
  Eye,
  ListFilter,
  MapPin,
  Pencil,
  Plus,
  RefreshCw,
  Search,
  Trash2,
  Truck,
  Wrench,
} from "lucide-react";
import { useState } from "react";
import { ScheduleDetailModal } from "@/components/schedule/schedule-detail-modal";
import { ScheduleEventModal } from "@/components/schedule/schedule-event-modal";
import { ScheduleStatsCards } from "@/components/schedule/schedule-stats-cards";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { useSchedule } from "@/hooks/use-schedule";
import { formatDate } from "@/lib/utils";
import { ScheduleEvent, ScheduleEventStatus, ScheduleEventType } from "@/types/schedule";

export default function AgendaPage() {
  const {
    events,
    customers,
    equipmentList,
    stats,
    viewMode,
    filters,
    isLoading,
    isSaving,
    selectedEvent,
    setViewMode,
    setSelectedEvent,
    setSearch,
    setTypeFilter,
    setStatusFilter,
    loadData,
    loadEventDetails,
    createEvent,
    updateEvent,
    completeEvent,
    deleteEvent,
  } = useSchedule();

  const [isFormModalOpen, setIsFormModalOpen] = useState(false);
  const [eventToEdit, setEventToEdit] = useState<ScheduleEvent | null>(null);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);

  // Month navigation for Calendar grid
  const [currentDate, setCurrentDate] = useState(new Date());

  const handleOpenCreateModal = () => {
    setEventToEdit(null);
    setIsFormModalOpen(true);
  };

  const handleOpenEditModal = (evt: ScheduleEvent) => {
    setEventToEdit(evt);
    setIsFormModalOpen(true);
  };

  const handleOpenDetailModal = async (evt: ScheduleEvent) => {
    setIsDetailModalOpen(true);
    await loadEventDetails(evt.id);
  };

  const handleFormSubmit = async (data: any) => {
    if (eventToEdit) {
      await updateEvent(eventToEdit.id, data);
    } else {
      await createEvent(data);
    }
  };

  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</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>;
    }
  };

  // Month Calendar Helper Functions
  const getDaysInMonth = (year: number, month: number) => {
    return new Date(year, month + 1, 0).getDate();
  };

  const getFirstDayOfMonth = (year: number, month: number) => {
    return new Date(year, month, 1).getDay();
  };

  const year = currentDate.getFullYear();
  const month = currentDate.getMonth();
  const monthName = currentDate.toLocaleString("pt-BR", { month: "long", year: "numeric" });

  const daysInMonth = getDaysInMonth(year, month);
  const firstDay = getFirstDayOfMonth(year, month);
  const daysArray = Array.from({ length: daysInMonth }, (_, i) => i + 1);
  const leadingEmptyDays = Array.from({ length: firstDay }, (_, i) => i);

  const prevMonth = () => {
    setCurrentDate(new Date(year, month - 1, 1));
  };

  const nextMonth = () => {
    setCurrentDate(new Date(year, month + 1, 1));
  };

  return (
    <div className="space-y-6">
      {/* Header com Título e Ação */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <p className="text-sm font-medium text-muted-foreground">Dashboard / Operacional & Logística</p>
          <h1 className="mt-1 text-2xl font-bold tracking-tight text-foreground sm:text-3xl">
            Agenda Operacional & Despacho
          </h1>
        </div>

        <div className="flex flex-wrap items-center gap-2">
          {/* Alternador de Modo de Visualização */}
          <div className="flex rounded-lg border bg-muted/50 p-1">
            <button
              onClick={() => setViewMode("CALENDAR")}
              className={`flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold transition ${
                viewMode === "CALENDAR"
                  ? "bg-background text-foreground shadow-xs"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              <CalendarIcon className="h-3.5 w-3.5" /> Grade Mensal
            </button>
            <button
              onClick={() => setViewMode("LIST")}
              className={`flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold transition ${
                viewMode === "LIST"
                  ? "bg-background text-foreground shadow-xs"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              <ListFilter className="h-3.5 w-3.5" /> Lista Cronológica
            </button>
          </div>

          <Button variant="secondary" size="icon" onClick={() => loadData()} title="Atualizar dados">
            <RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
          </Button>

          <Button onClick={handleOpenCreateModal} className="shadow-xs">
            <Plus className="mr-1.5 h-4 w-4" /> Novo Agendamento
          </Button>
        </div>
      </div>

      {/* Cartões de Estatísticas / KPIs */}
      <ScheduleStatsCards
        stats={stats}
        activeFilter={filters.type || "ALL"}
        onFilterClick={(typeKey) => setTypeFilter(typeKey as any)}
      />

      {/* Painel Principal */}
      <Card className="overflow-hidden shadow-xs border">
        {/* Barra de Busca e Filtros */}
        <div className="flex flex-col gap-4 border-b bg-card p-4 lg:flex-row lg:items-center lg:justify-between">
          <div className="relative flex-1 max-w-md">
            <Search className="pointer-events-none absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
            <Input
              value={filters.search || ""}
              onChange={(e) => setSearch(e.target.value)}
              className="pl-9"
              placeholder="Buscar agendamento por título, cliente ou máquina..."
            />
          </div>

          <div className="flex flex-wrap items-center gap-3">
            {/* Filtro por Tipo */}
            <select
              value={filters.type || "ALL"}
              onChange={(e) => setTypeFilter(e.target.value as any)}
              className="rounded-md border border-input bg-background px-3 py-1.5 text-xs font-medium shadow-xs focus:outline-hidden focus:ring-1 focus:ring-ring"
            >
              <option value="ALL">Todos os Tipos</option>
              <option value="DELIVERY">Entregas (Mobilização)</option>
              <option value="RETURN">Devoluções (Coleta)</option>
              <option value="MAINTENANCE">Manutenções</option>
              <option value="INSPECTION">Vistorias Técnicas</option>
            </select>

            {/* Filtro por Status */}
            <select
              value={filters.status || "ALL"}
              onChange={(e) => setStatusFilter(e.target.value as any)}
              className="rounded-md border border-input bg-background px-3 py-1.5 text-xs font-medium shadow-xs focus:outline-hidden focus:ring-1 focus:ring-ring"
            >
              <option value="ALL">Todos os Status</option>
              <option value="SCHEDULED">Agendados</option>
              <option value="IN_TRANSIT">Em Trânsito</option>
              <option value="COMPLETED">Concluídos</option>
              <option value="CANCELED">Cancelados</option>
            </select>
          </div>
        </div>

        {/* Visualização de Grade Mensal (Calendário) */}
        {viewMode === "CALENDAR" && (
          <div className="p-4">
            {/* Controles de Navegação do Mês */}
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-lg font-bold capitalize text-foreground flex items-center gap-2">
                <CalendarIcon className="h-5 w-5 text-primary" /> {monthName}
              </h2>
              <div className="flex items-center gap-2">
                <Button variant="secondary" size="sm" onClick={prevMonth}>
                  <ChevronLeft className="h-4 w-4 mr-1" /> Mês Anterior
                </Button>
                <Button variant="secondary" size="sm" onClick={() => setCurrentDate(new Date())}>
                  Hoje
                </Button>
                <Button variant="secondary" size="sm" onClick={nextMonth}>
                  Próximo Mês <ChevronRight className="h-4 w-4 ml-1" />
                </Button>
              </div>
            </div>

            {/* Grade do Calendário */}
            <div className="grid grid-cols-7 gap-px bg-border rounded-xl overflow-hidden border">
              {/* Dias da Semana */}
              {["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"].map((d) => (
                <div key={d} className="bg-muted/80 p-2 text-center text-xs font-bold text-muted-foreground uppercase">
                  {d}
                </div>
              ))}

              {/* Dias vazios que antecedem o mês */}
              {leadingEmptyDays.map((i) => (
                <div key={`empty-${i}`} className="bg-card/40 p-2 min-h-[110px]" />
              ))}

              {/* Dias do Mês */}
              {daysArray.map((day) => {
                const dayStr = `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
                const dayEvents = events.filter((e) => e.startDate.startsWith(dayStr));
                const isToday = new Date().toISOString().startsWith(dayStr);

                return (
                  <div
                    key={day}
                    className={`bg-card p-2 min-h-[110px] flex flex-col justify-between transition-colors hover:bg-muted/30 ${
                      isToday ? "ring-2 ring-primary/40 bg-primary/5 font-bold" : ""
                    }`}
                  >
                    <div className="flex items-center justify-between mb-1">
                      <span className={`text-xs font-semibold rounded-full px-2 py-0.5 ${isToday ? "bg-primary text-primary-foreground font-bold" : "text-muted-foreground"}`}>
                        {day}
                      </span>
                      {dayEvents.length > 0 && (
                        <span className="text-[10px] font-bold text-muted-foreground bg-muted px-1.5 py-0.5 rounded-full">
                          {dayEvents.length}
                        </span>
                      )}
                    </div>

                    <div className="space-y-1 overflow-y-auto max-h-[80px]">
                      {dayEvents.map((evt) => (
                        <div
                          key={evt.id}
                          onClick={() => handleOpenDetailModal(evt)}
                          className={`text-[11px] p-1 rounded-md border truncate cursor-pointer transition-all hover:scale-[1.02] shadow-2xs ${
                            evt.type === "DELIVERY"
                              ? "bg-emerald-500/10 border-emerald-500/30 text-emerald-700 dark:text-emerald-300 font-semibold"
                              : evt.type === "RETURN"
                              ? "bg-blue-500/10 border-blue-500/30 text-blue-700 dark:text-blue-300 font-semibold"
                              : evt.type === "MAINTENANCE"
                              ? "bg-purple-500/10 border-purple-500/30 text-purple-700 dark:text-purple-300 font-semibold"
                              : "bg-amber-500/10 border-amber-500/30 text-amber-700 dark:text-amber-300 font-semibold"
                          }`}
                          title={evt.title}
                        >
                          {evt.type === "DELIVERY" && "🚚 "}
                          {evt.type === "RETURN" && "📦 "}
                          {evt.type === "MAINTENANCE" && "🔧 "}
                          {evt.type === "INSPECTION" && "📋 "}
                          {evt.title}
                        </div>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* Visualização em Lista Cronológica */}
        {viewMode === "LIST" && (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[850px] text-left text-sm">
              <thead className="bg-muted/50 text-xs uppercase text-muted-foreground">
                <tr>
                  <th className="px-4 py-3.5 font-medium">Data / Evento</th>
                  <th className="px-4 py-3.5 font-medium">Tipo</th>
                  <th className="px-4 py-3.5 font-medium">Cliente / Obra</th>
                  <th className="px-4 py-3.5 font-medium">Equipamento</th>
                  <th className="px-4 py-3.5 font-medium">Motorista / Técnico</th>
                  <th className="px-4 py-3.5 font-medium">Status</th>
                  <th className="w-20 px-4 py-3.5 text-right font-medium">Ações</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {isLoading ? (
                  <tr>
                    <td colSpan={7} className="p-8 text-center text-muted-foreground">
                      <RefreshCw className="mx-auto h-6 w-6 animate-spin text-primary" />
                      <p className="mt-2 text-xs">Carregando compromissos da agenda...</p>
                    </td>
                  </tr>
                ) : events.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="p-12 text-center text-muted-foreground">
                      Nenhum compromisso encontrado para os filtros selecionados.
                    </td>
                  </tr>
                ) : (
                  events.map((evt) => (
                    <tr key={evt.id} className="group hover:bg-muted/40 transition-colors">
                      <td className="px-4 py-3.5">
                        <div className="flex items-center gap-3">
                          <div className="rounded-lg border bg-background p-2 group-hover:border-primary/40 transition-colors">
                            <Clock className="h-4 w-4 text-primary" />
                          </div>
                          <div>
                            <p
                              onClick={() => handleOpenDetailModal(evt)}
                              className="font-bold text-foreground hover:text-primary hover:underline cursor-pointer"
                            >
                              {evt.title}
                            </p>
                            <p className="text-xs text-muted-foreground font-mono">
                              Data: {formatDate(evt.startDate)}
                            </p>
                          </div>
                        </div>
                      </td>

                      <td className="px-4 py-3.5">{renderTypeBadge(evt.type)}</td>

                      <td className="px-4 py-3.5">
                        <p className="font-semibold text-foreground">
                          {evt.customer?.name || "Cliente não informado"}
                        </p>
                        {evt.location && (
                          <p className="text-xs text-muted-foreground flex items-center gap-1 mt-0.5 truncate max-w-[200px]">
                            <MapPin className="h-3 w-3 text-rose-500" /> {evt.location}
                          </p>
                        )}
                      </td>

                      <td className="px-4 py-3.5">
                        <p className="font-medium text-foreground">
                          {evt.equipment
                            ? `${evt.equipment.brand} ${evt.equipment.model}`
                            : "Máquina Industrial"}
                        </p>
                        <p className="text-xs text-muted-foreground font-mono">
                          {evt.equipment?.code || "EQ-100"}
                        </p>
                      </td>

                      <td className="px-4 py-3.5 text-xs text-muted-foreground font-medium">
                        {evt.technician || "Equipe de Despacho"}
                      </td>

                      <td className="px-4 py-3.5">{renderStatusBadge(evt.status)}</td>

                      <td className="px-4 py-3.5 text-right">
                        <div className="flex items-center justify-end gap-1">
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => handleOpenDetailModal(evt)}
                            title="Ver Detalhes"
                          >
                            <Eye className="h-4 w-4 text-muted-foreground hover:text-foreground" />
                          </Button>

                          {evt.status !== "COMPLETED" && (
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => completeEvent(evt.id)}
                              title="Marcar como Concluído"
                              className="text-emerald-600 hover:bg-emerald-500/10"
                            >
                              <CheckCircle2 className="h-4 w-4" />
                            </Button>
                          )}

                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => handleOpenEditModal(evt)}
                            title="Editar"
                          >
                            <Pencil className="h-4 w-4 text-muted-foreground hover:text-foreground" />
                          </Button>

                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => {
                              if (confirm(`Tem certeza que deseja excluir o agendamento ${evt.title}?`)) {
                                deleteEvent(evt.id);
                              }
                            }}
                            title="Excluir"
                            className="text-rose-500 hover:bg-rose-500/10 hover:text-rose-600"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        )}
      </Card>

      {/* Modal de Formulário (Novo / Editar Agendamento) */}
      <ScheduleEventModal
        isOpen={isFormModalOpen}
        onClose={() => setIsFormModalOpen(false)}
        onSubmit={handleFormSubmit}
        eventToEdit={eventToEdit}
        customers={customers}
        equipmentList={equipmentList}
        isSaving={isSaving}
      />

      {/* Modal de Detalhes do Compromisso */}
      <ScheduleDetailModal
        isOpen={isDetailModalOpen}
        onClose={() => setIsDetailModalOpen(false)}
        event={selectedEvent}
        onEdit={(evt) => {
          setIsDetailModalOpen(false);
          handleOpenEditModal(evt);
        }}
        onDelete={(id) => deleteEvent(id)}
        onComplete={(id) => completeEvent(id)}
      />
    </div>
  );
}
