"use client";

import { useState } from "react";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Loader2, Check } from "lucide-react";
import { cn } from "@/lib/utils";

interface Props {
  doctors: { id: string; full_name: string; specialty: string | null; color: string | null }[];
  patients: { id: string; first_name: string; last_name: string; phone: string | null }[];
  defaultDate?: string | null;
  onSuccess: () => void;
}

export function AppointmentForm({ doctors, patients, defaultDate, onSuccess }: Props) {
  const supabase = createClient();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [patientOpen, setPatientOpen] = useState(false);
  const [selectedPatientId, setSelectedPatientId] = useState("");
  const [selectedPatientLabel, setSelectedPatientLabel] = useState("");

  const defaultDateValue = defaultDate ? defaultDate.slice(0, 10) : new Date().toISOString().slice(0, 10);
  const defaultTime = defaultDate && defaultDate.length > 10 ? defaultDate.slice(11, 16) : "09:00";

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    setLoading(true);

    const form = new FormData(e.currentTarget);
    const date = form.get("date") as string;
    const time = form.get("time") as string;
    const duration = parseInt(form.get("duration") as string) || 30;
    const starts_at = new Date(`${date}T${time}`).toISOString();
    const ends_at = new Date(new Date(`${date}T${time}`).getTime() + duration * 60000).toISOString();

    const { data: { user } } = await supabase.auth.getUser();
    if (!user) { setError("No autenticado"); setLoading(false); return; }
    const { data: profile } = await supabase.from("users").select("clinic_id").eq("id", user.id).single();
    if (!profile) { setError("Perfil no encontrado"); setLoading(false); return; }

    const { error: err } = await supabase.from("appointments").insert({
      clinic_id: profile.clinic_id,
      patient_id: selectedPatientId,
      doctor_id: form.get("doctor_id") as string,
      starts_at,
      ends_at,
      type: form.get("type") as string,
      reason: (form.get("reason") as string) || null,
      notes: (form.get("notes") as string) || null,
      status: "scheduled",
      created_by: user.id,
    });

    if (err) {
      setError(err.message);
      setLoading(false);
      return;
    }

    onSuccess();
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {error && <div className="rounded-lg bg-destructive/10 p-3 text-sm text-destructive">{error}</div>}

      {/* Patient search */}
      <div className="space-y-2">
        <Label>Paciente *</Label>
        <Popover open={patientOpen} onOpenChange={setPatientOpen}>
          <PopoverTrigger asChild>
            <Button variant="outline" className="w-full justify-start h-10 font-normal">
              {selectedPatientLabel || <span className="text-muted-foreground">Buscar paciente...</span>}
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-full p-0" align="start">
            <Command>
              <CommandInput placeholder="Buscar por nombre..." />
              <CommandList>
                <CommandEmpty>Sin resultados.</CommandEmpty>
                <CommandGroup>
                  {patients.map((p) => (
                    <CommandItem
                      key={p.id}
                      value={`${p.first_name} ${p.last_name} ${p.phone || ""}`}
                      onSelect={() => {
                        setSelectedPatientId(p.id);
                        setSelectedPatientLabel(`${p.first_name} ${p.last_name}`);
                        setPatientOpen(false);
                      }}
                    >
                      <Check className={cn("mr-2 h-4 w-4", selectedPatientId === p.id ? "opacity-100" : "opacity-0")} />
                      <div>
                        <div className="font-medium">{p.first_name} {p.last_name}</div>
                        {p.phone && <div className="text-xs text-muted-foreground">{p.phone}</div>}
                      </div>
                    </CommandItem>
                  ))}
                </CommandGroup>
              </CommandList>
            </Command>
          </PopoverContent>
        </Popover>
      </div>

      {/* Doctor */}
      <div className="space-y-2">
        <Label>Doctor *</Label>
        <Select name="doctor_id" required>
          <SelectTrigger className="h-10"><SelectValue placeholder="Seleccionar doctor" /></SelectTrigger>
          <SelectContent>
            {doctors.map((d) => (
              <SelectItem key={d.id} value={d.id}>
                {d.full_name}{d.specialty ? ` - ${d.specialty}` : ""}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Date & Time */}
      <div className="grid grid-cols-3 gap-3">
        <div className="space-y-2">
          <Label>Fecha *</Label>
          <Input name="date" type="date" defaultValue={defaultDateValue} required className="h-10" />
        </div>
        <div className="space-y-2">
          <Label>Hora *</Label>
          <Input name="time" type="time" defaultValue={defaultTime} required className="h-10" />
        </div>
        <div className="space-y-2">
          <Label>Duracion</Label>
          <Select name="duration" defaultValue="30">
            <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="15">15 min</SelectItem>
              <SelectItem value="30">30 min</SelectItem>
              <SelectItem value="45">45 min</SelectItem>
              <SelectItem value="60">1 hora</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Type */}
      <div className="space-y-2">
        <Label>Tipo de cita</Label>
        <Select name="type" defaultValue="seguimiento">
          <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
          <SelectContent>
            <SelectItem value="primera_vez">Primera vez</SelectItem>
            <SelectItem value="seguimiento">Seguimiento</SelectItem>
            <SelectItem value="urgencia">Urgencia</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Reason */}
      <div className="space-y-2">
        <Label>Motivo</Label>
        <Input name="reason" placeholder="Motivo de la consulta" className="h-10" />
      </div>

      {/* Notes */}
      <div className="space-y-2">
        <Label>Notas</Label>
        <Textarea name="notes" rows={2} placeholder="Notas adicionales..." />
      </div>

      <Button type="submit" disabled={loading || !selectedPatientId} className="w-full h-10">
        {loading ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Agendando...</> : "Agendar cita"}
      </Button>
    </form>
  );
}
