"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
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 { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Loader2, Save, ArrowLeft } from "lucide-react";
import Link from "next/link";
import type { Patient } from "@/types/database";

interface PatientFormProps {
  patient?: Patient;
}

export function PatientForm({ patient }: PatientFormProps) {
  const router = useRouter();
  const supabase = createClient();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isEdit = !!patient;

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

    const formData = new FormData(e.currentTarget);
    const {
      data: { user },
    } = await supabase.auth.getUser();
    if (!user) {
      setError("No autenticado");
      setLoading(false);
      return;
    }

    try {
      if (isEdit) {
        const updates: Record<string, unknown> = {};
        const fields = [
          "first_name",
          "last_name",
          "date_of_birth",
          "gender",
          "curp",
          "phone",
          "email",
          "blood_type",
          "notes",
          "source",
        ];
        for (const field of fields) {
          updates[field] = (formData.get(field) as string) || null;
        }
        const { error: err } = await supabase
          .from("patients")
          .update(updates)
          .eq("id", patient!.id);
        if (err) throw err;
      } else {
        const { data: profile } = await supabase
          .from("users")
          .select("clinic_id")
          .eq("id", user.id)
          .single();
        if (!profile) throw new Error("Perfil no encontrado");

        const patientData = {
          clinic_id: profile.clinic_id,
          first_name: formData.get("first_name") as string,
          last_name: formData.get("last_name") as string,
          date_of_birth: (formData.get("date_of_birth") as string) || null,
          gender: (formData.get("gender") as string) || null,
          curp: (formData.get("curp") as string) || null,
          phone: (formData.get("phone") as string) || null,
          email: (formData.get("email") as string) || null,
          blood_type: (formData.get("blood_type") as string) || null,
          notes: (formData.get("notes") as string) || null,
          source: (formData.get("source") as string) || null,
        };
        const { error: err } = await supabase
          .from("patients")
          .insert(patientData);
        if (err) throw err;
      }
      router.push("/patients");
      router.refresh();
    } catch (err: unknown) {
      const message =
        err instanceof Error ? err.message : "Error al guardar paciente";
      setError(message);
      setLoading(false);
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Datos personales</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          {error && (
            <div className="rounded-lg bg-destructive/10 p-3 text-sm text-destructive">
              {error}
            </div>
          )}

          {/* Name */}
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="first_name">Nombre(s) *</Label>
              <Input
                id="first_name"
                name="first_name"
                defaultValue={patient?.first_name}
                required
                className="h-11"
                placeholder="Juan Carlos"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="last_name">Apellidos *</Label>
              <Input
                id="last_name"
                name="last_name"
                defaultValue={patient?.last_name}
                required
                className="h-11"
                placeholder="Perez Lopez"
              />
            </div>
          </div>

          {/* Demographics */}
          <div className="grid gap-4 sm:grid-cols-3">
            <div className="space-y-2">
              <Label htmlFor="date_of_birth">Fecha de nacimiento</Label>
              <Input
                id="date_of_birth"
                name="date_of_birth"
                type="date"
                defaultValue={patient?.date_of_birth || ""}
                className="h-11"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="gender">Genero</Label>
              <Select name="gender" defaultValue={patient?.gender || ""}>
                <SelectTrigger className="h-11">
                  <SelectValue placeholder="Seleccionar" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="M">Masculino</SelectItem>
                  <SelectItem value="F">Femenino</SelectItem>
                  <SelectItem value="otro">Otro</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="blood_type">Tipo de sangre</Label>
              <Select
                name="blood_type"
                defaultValue={patient?.blood_type || ""}
              >
                <SelectTrigger className="h-11">
                  <SelectValue placeholder="Seleccionar" />
                </SelectTrigger>
                <SelectContent>
                  {["A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"].map(
                    (t) => (
                      <SelectItem key={t} value={t}>
                        {t}
                      </SelectItem>
                    )
                  )}
                </SelectContent>
              </Select>
            </div>
          </div>

          <Separator />

          {/* Contact */}
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="phone">Telefono</Label>
              <Input
                id="phone"
                name="phone"
                type="tel"
                defaultValue={patient?.phone || ""}
                className="h-11"
                placeholder="55 1234 5678"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="email">Correo electronico</Label>
              <Input
                id="email"
                name="email"
                type="email"
                defaultValue={patient?.email || ""}
                className="h-11"
                placeholder="paciente@email.com"
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="curp">CURP</Label>
            <Input
              id="curp"
              name="curp"
              defaultValue={patient?.curp || ""}
              className="h-11 font-mono uppercase"
              placeholder="XXXX000000XXXXXXXX"
              maxLength={18}
            />
          </div>

          <Separator />

          {/* Source */}
          <div className="space-y-2">
            <Label htmlFor="source">Como nos encontro?</Label>
            <Select name="source" defaultValue={patient?.source || ""}>
              <SelectTrigger className="h-11">
                <SelectValue placeholder="Seleccionar" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="referido">Referido</SelectItem>
                <SelectItem value="facebook">Facebook</SelectItem>
                <SelectItem value="google">Google</SelectItem>
                <SelectItem value="instagram">Instagram</SelectItem>
                <SelectItem value="directo">Llego directo</SelectItem>
                <SelectItem value="otro">Otro</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Notes */}
          <div className="space-y-2">
            <Label htmlFor="notes">Notas</Label>
            <Textarea
              id="notes"
              name="notes"
              defaultValue={patient?.notes || ""}
              rows={3}
              placeholder="Observaciones adicionales..."
            />
          </div>
        </CardContent>
        <CardFooter className="flex justify-between border-t pt-6">
          <Link href="/patients">
            <Button type="button" variant="ghost" className="gap-2">
              <ArrowLeft className="h-4 w-4" /> Cancelar
            </Button>
          </Link>
          <Button
            type="submit"
            disabled={loading}
            className="gap-2 min-w-[140px]"
          >
            {loading ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" /> Guardando...
              </>
            ) : (
              <>
                <Save className="h-4 w-4" />{" "}
                {isEdit ? "Actualizar" : "Guardar paciente"}
              </>
            )}
          </Button>
        </CardFooter>
      </Card>
    </form>
  );
}
