"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { ChevronLeft, ChevronRight, Plus, Pencil, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import AppointmentDialog from "./AppointmentDialog"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"

type Client = {
  id: string
  name: string
  phone: string
}

type Appointment = {
  id: string
  clientId: string
  client: Client
  date: Date
  duration: number
  type: string
  status: string
  notes: string | null
}

type AppointmentsCalendarProps = {
  appointments: Appointment[]
  clients: Client[]
}

const statusColors: Record<string, string> = {
  SCHEDULED: "bg-blue-500",
  CONFIRMED: "bg-green-500",
  COMPLETED: "bg-gray-400",
  CANCELLED: "bg-red-500",
  NO_SHOW: "bg-yellow-500",
}

const statusLabels: Record<string, string> = {
  SCHEDULED: "Programmé",
  CONFIRMED: "Confirmé",
  COMPLETED: "Terminé",
  CANCELLED: "Annulé",
  NO_SHOW: "Absent",
}

const typeLabels: Record<string, string> = {
  CONSULTATION: "Consultation",
  CONTROL: "Contrôle",
  DELIVERY: "Livraison",
  REPAIR: "Réparation",
  OTHER: "Autre",
}

export default function AppointmentsCalendar({ appointments, clients }: AppointmentsCalendarProps) {
  const router = useRouter()
  const [currentDate, setCurrentDate] = useState(new Date())
  const [appointmentList, setAppointmentList] = useState(appointments)
  const [selectedDate, setSelectedDate] = useState<Date>(new Date())
  const [editAppointment, setEditAppointment] = useState<Appointment | null>(null)
  const [deleteAppointment, setDeleteAppointment] = useState<Appointment | null>(null)
  const [deleting, setDeleting] = useState(false)
  const [showNewDialog, setShowNewDialog] = useState(false)

  const year = currentDate.getFullYear()
  const month = currentDate.getMonth()

  const firstDayOfMonth = new Date(year, month, 1)
  const lastDayOfMonth = new Date(year, month + 1, 0)
  const firstDayWeek = firstDayOfMonth.getDay()

  const daysInMonth = lastDayOfMonth.getDate()
  const startingDayOfWeek = firstDayWeek === 0 ? 6 : firstDayWeek - 1

  const monthNames = [
    "Janvier", "Février", "Mars", "Avril", "Mai", "Juin",
    "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
  ]

  const dayNames = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"]

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

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

  const goToToday = () => {
    const today = new Date()
    setCurrentDate(today)
    setSelectedDate(today)
  }

  const getAppointmentsForDay = (day: number) => {
    const dayDate = new Date(year, month, day)
    return appointments.filter(apt => {
      const aptDate = new Date(apt.date)
      return aptDate.getDate() === day &&
             aptDate.getMonth() === month &&
             aptDate.getFullYear() === year
    }).sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
  }

  const isToday = (day: number) => {
    const today = new Date()
    return day === today.getDate() &&
            month === today.getMonth() &&
            year === today.getFullYear()
  }

  const isSelected = (day: number) => {
    if (!selectedDate) return false
    return day === selectedDate.getDate() &&
           month === selectedDate.getMonth() &&
           year === selectedDate.getFullYear()
  }

  const formatTime = (date: Date) => {
    return new Date(date).toLocaleTimeString('fr-MA', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const days = []
  for (let i = 0; i < startingDayOfWeek; i++) {
    days.push(null)
  }
  for (let i = 1; i <= daysInMonth; i++) {
    days.push(i)
  }

  const handleAppointmentCreated = (newApt: any) => {
    setAppointmentList([...appointmentList, { ...newApt, date: new Date(newApt.date) }])
    router.refresh()
  }

  const handleDelete = async () => {
    if (!deleteAppointment) return
    setDeleting(true)
    try {
      const response = await fetch(`/api/appointments/${deleteAppointment.id}`, { method: 'DELETE' })
      if (response.ok) {
        setAppointmentList(appointmentList.filter(a => a.id !== deleteAppointment.id))
        setDeleteAppointment(null)
        router.refresh()
      }
    } catch (error) {
      console.error('Error deleting appointment:', error)
    } finally {
      setDeleting(false)
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <Button variant="outline" size="icon" onClick={prevMonth}>
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <h2 className="text-xl font-semibold min-w-[180px] text-center">
              {monthNames[month]} {year}
            </h2>
            <Button variant="outline" size="icon" onClick={nextMonth}>
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
          <Button variant="outline" size="sm" onClick={goToToday}>
            Aujourd'hui
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden">
        {dayNames.map(day => (
          <div key={day} className="bg-muted p-2 text-center text-sm font-medium">
            {day}
          </div>
        ))}
        {days.map((day, index) => {
          const dayAppointments = day ? getAppointmentsForDay(day) : []
          return (
            <div
              key={index}
              className={`min-h-[120px] bg-background p-1 ${
                day ? "cursor-pointer hover:bg-muted/50" : "bg-muted/30"
              } ${isSelected(day || 0) ? "ring-2 ring-teal-500 ring-inset bg-teal-50/50" : ""} ${day && isToday(day) && !isSelected(day) ? "ring-2 ring-teal-400 ring-inset" : ""}`}
              onClick={() => day && setSelectedDate(new Date(year, month, day))}
            >
              {day && (
                <>
                  <div className={`text-sm p-1 ${isToday(day) ? "font-bold text-teal-600" : ""}`}>
                    {day}
                  </div>
                  <div className="space-y-1">
                    {dayAppointments.slice(0, 3).map(apt => (
                      <div
                        key={apt.id}
                        className={`text-xs px-1 py-0.5 rounded text-white truncate ${statusColors[apt.status] || "bg-gray-400"}`}
                        title={`${formatTime(apt.date)} - ${apt.client?.name || 'Client'} (${typeLabels[apt.type] || apt.type})`}
                      >
                        {formatTime(apt.date)} {apt.client?.name?.split(' ')[0] || ''}
                      </div>
                    ))}
                    {dayAppointments.length > 3 && (
                      <div className="text-xs text-muted-foreground px-1">
                        +{dayAppointments.length - 3} autres
                      </div>
                    )}
                  </div>
                </>
              )}
            </div>
          )
        })}
      </div>

      {selectedDate && (
        <div className="bg-muted/50 rounded-lg p-4">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold">
              {selectedDate.toLocaleDateString('fr-MA', {
                weekday: 'long',
                day: 'numeric',
                month: 'long'
              })}
            </h3>
            <div className="flex gap-2">
              <Button size="sm" className="bg-teal-600 hover:bg-teal-700" onClick={() => setShowNewDialog(true)}>
                <Plus className="mr-1 h-4 w-4" />
                Ajouter
              </Button>
              <Button variant="ghost" size="sm" onClick={() => setSelectedDate(new Date())}>
                Fermer
              </Button>
            </div>
          </div>
          
          {getAppointmentsForDay(selectedDate.getDate()).length === 0 ? (
            <p className="text-muted-foreground text-sm">Aucun rendez-vous ce jour</p>
          ) : (
            <div className="space-y-2">
              {getAppointmentsForDay(selectedDate.getDate()).map(apt => (
                <div key={apt.id} className="flex items-center gap-3 bg-background p-3 rounded-lg border">
                  <div className={`w-1 h-12 rounded-full ${statusColors[apt.status] || "bg-gray-400"}`} />
                  <div className="flex-1">
                    <div className="flex items-center gap-2">
                      <span className="font-medium">{apt.client?.name || 'Client'}</span>
                      <span className="text-sm text-muted-foreground">({apt.client?.phone || '-'})</span>
                    </div>
                    <div className="flex items-center gap-4 text-sm text-muted-foreground">
                      <span>{formatTime(apt.date)} - {apt.duration} min</span>
                      <span className="px-2 py-0.5 bg-muted rounded text-xs">{typeLabels[apt.type] || apt.type}</span>
                    </div>
                    {apt.notes && (
                      <p className="text-sm text-muted-foreground mt-1">{apt.notes}</p>
                    )}
                  </div>
                  <div className="flex items-center gap-2">
                    <span className={`text-xs px-2 py-1 rounded ${
                      apt.status === 'CONFIRMED' ? 'bg-green-100 text-green-700' :
                      apt.status === 'SCHEDULED' ? 'bg-blue-100 text-blue-700' :
                      apt.status === 'COMPLETED' ? 'bg-gray-100 text-gray-700' :
                      apt.status === 'CANCELLED' ? 'bg-red-100 text-red-700' :
                      'bg-yellow-100 text-yellow-700'
                    }`}>
                      {statusLabels[apt.status]}
                    </span>
                    <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => setEditAppointment(apt)}>
                      <Pencil className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8 text-red-500" onClick={() => setDeleteAppointment(apt)}>
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      <div className="flex items-center gap-4 text-sm text-muted-foreground">
        <span className="flex items-center gap-1">
          <span className="w-3 h-3 rounded bg-blue-500"></span> Programmé
        </span>
        <span className="flex items-center gap-1">
          <span className="w-3 h-3 rounded bg-green-500"></span> Confirmé
        </span>
        <span className="flex items-center gap-1">
          <span className="w-3 h-3 rounded bg-gray-400"></span> Terminé
        </span>
        <span className="flex items-center gap-1">
          <span className="w-3 h-3 rounded bg-red-500"></span> Annulé
        </span>
      </div>

      <AppointmentDialog 
        clients={clients} 
        appointment={editAppointment} 
        trigger={<span />} 
        open={!!editAppointment} 
        onOpenChange={(open) => !open && setEditAppointment(null)} 
      />

      <Dialog open={!!deleteAppointment} onOpenChange={(open) => !open && setDeleteAppointment(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Supprimer le rendez-vous</DialogTitle>
            <DialogDescription>
              Êtes-vous sûr de vouloir supprimer ce rendez-vous ? Cette action est irréversible.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteAppointment(null)}>Annuler</Button>
            <Button variant="destructive" onClick={handleDelete} disabled={deleting}>
              {deleting ? 'Suppression...' : 'Supprimer'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AppointmentDialog 
        clients={clients}
        open={showNewDialog}
        onOpenChange={(open) => {
          setShowNewDialog(open)
          if (!open) router.refresh()
        }}
        defaultDate={selectedDate ? selectedDate.toISOString().split('T')[0] : new Date().toISOString().split('T')[0]}
      />
    </div>
  )
}
