"use client";

import "@/app/fullcalendar.css";
import { useEffect, useState, useRef } from "react";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import { createClient } from "@/lib/supabase/client";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { AppointmentForm } from "./appointment-form";
import { AppointmentDetail } from "./appointment-detail";
import { Plus } from "lucide-react";

const statusColors: Record<string, string> = {
  scheduled: "#3b82f6",
  confirmed: "#10b981",
  in_progress: "#f59e0b",
  completed: "#6b7280",
  cancelled: "#ef4444",
  no_show: "#8b5cf6",
};

const statusLabels: Record<string, string> = {
  scheduled: "Programada",
  confirmed: "Confirmada",
  in_progress: "En consulta",
  completed: "Completada",
  cancelled: "Cancelada",
  no_show: "No asistio",
};

interface CalendarProps {
  doctors: { id: string; full_name: string; specialty: string | null; color: string | null }[];
  patients: { id: string; first_name: string; last_name: string; phone: string | null }[];
}

export function AppointmentCalendar({ doctors, patients }: CalendarProps) {
  const supabase = createClient();
  const calendarRef = useRef<FullCalendar>(null);
  const [events, setEvents] = useState<any[]>([]);
  const [selectedDoctor, setSelectedDoctor] = useState<string>("all");
  const [showNewDialog, setShowNewDialog] = useState(false);
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedDate, setSelectedDate] = useState<string | null>(null);
  const [selectedAppointment, setSelectedAppointment] = useState<any>(null);

  async function fetchAppointments() {
    let query = supabase
      .from("appointments")
      .select("*, patient:patients(id, first_name, last_name, phone), doctor:users(id, full_name, color, specialty)")
      .order("starts_at");

    if (selectedDoctor !== "all") {
      query = query.eq("doctor_id", selectedDoctor);
    }

    const { data } = await query;
    if (data) {
      setEvents(data.map((apt: any) => ({
        id: apt.id,
        title: `${apt.patient?.first_name} ${apt.patient?.last_name}`,
        start: apt.starts_at,
        end: apt.ends_at,
        backgroundColor: statusColors[apt.status] || "#3b82f6",
        borderColor: statusColors[apt.status] || "#3b82f6",
        extendedProps: { ...apt },
      })));
    }
  }

  useEffect(() => {
    fetchAppointments();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedDoctor]);

  function handleDateClick(info: any) {
    setSelectedDate(info.dateStr);
    setShowNewDialog(true);
  }

  function handleEventClick(info: any) {
    setSelectedAppointment(info.event.extendedProps);
    setShowDetailDialog(true);
  }

  async function handleEventDrop(info: any) {
    const { id } = info.event;
    const starts_at = info.event.start.toISOString();
    const ends_at = info.event.end?.toISOString() || new Date(info.event.start.getTime() + 30 * 60000).toISOString();
    await supabase.from("appointments").update({ starts_at, ends_at }).eq("id", id);
    fetchAppointments();
  }

  return (
    <div className="space-y-4">
      {/* Controls */}
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <Select value={selectedDoctor} onValueChange={setSelectedDoctor}>
            <SelectTrigger className="w-[220px] h-10">
              <SelectValue placeholder="Todos los doctores" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Todos los doctores</SelectItem>
              {doctors.map((d) => (
                <SelectItem key={d.id} value={d.id}>{d.full_name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <div className="hidden sm:flex items-center gap-2">
            {Object.entries(statusLabels).slice(0, 4).map(([key, label]) => (
              <Badge key={key} variant="outline" className="gap-1.5 text-xs">
                <div className="h-2 w-2 rounded-full" style={{ backgroundColor: statusColors[key] }} />
                {label}
              </Badge>
            ))}
          </div>
        </div>
        <Button onClick={() => { setSelectedDate(null); setShowNewDialog(true); }} className="gap-2">
          <Plus className="h-4 w-4" /> Nueva cita
        </Button>
      </div>

      {/* Calendar */}
      <div className="rounded-xl border bg-card p-4 shadow-sm">
        <FullCalendar
          ref={calendarRef}
          plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
          initialView="timeGridWeek"
          headerToolbar={{
            left: "prev,next today",
            center: "title",
            right: "dayGridMonth,timeGridWeek,timeGridDay",
          }}
          locale="es"
          timeZone="America/Mexico_City"
          slotMinTime="07:00:00"
          slotMaxTime="21:00:00"
          allDaySlot={false}
          slotDuration="00:15:00"
          height="auto"
          contentHeight={650}
          events={events}
          editable={true}
          selectable={true}
          dateClick={handleDateClick}
          eventClick={handleEventClick}
          eventDrop={handleEventDrop}
          eventContent={(arg) => (
            <div className="flex flex-col gap-0.5 px-1 py-0.5 text-xs overflow-hidden">
              <span className="font-semibold truncate">{arg.event.title}</span>
              <span className="opacity-80 truncate">{arg.event.extendedProps?.doctor?.full_name}</span>
            </div>
          )}
          buttonText={{
            today: "Hoy",
            month: "Mes",
            week: "Semana",
            day: "Dia",
          }}
        />
      </div>

      {/* New Appointment Dialog */}
      <Dialog open={showNewDialog} onOpenChange={setShowNewDialog}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Nueva cita</DialogTitle>
          </DialogHeader>
          <AppointmentForm
            doctors={doctors}
            patients={patients}
            defaultDate={selectedDate}
            onSuccess={() => { setShowNewDialog(false); fetchAppointments(); }}
          />
        </DialogContent>
      </Dialog>

      {/* Appointment Detail Dialog */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Detalle de cita</DialogTitle>
          </DialogHeader>
          {selectedAppointment && (
            <AppointmentDetail
              appointment={selectedAppointment}
              onStatusChange={() => { setShowDetailDialog(false); fetchAppointments(); }}
            />
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
