"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Loader2, Save, Activity, Stethoscope, Plus, X } from "lucide-react";

interface Props {
  patientId: string;
}

export function ConsultationForm({ patientId }: Props) {
  const router = useRouter();
  const supabase = createClient();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [diagnoses, setDiagnoses] = useState<{ code: string; description: string; type: string }[]>([]);

  function addDiagnosis() {
    setDiagnoses([...diagnoses, { code: "", description: "", type: diagnoses.length === 0 ? "principal" : "secundario" }]);
  }

  function removeDiagnosis(index: number) {
    setDiagnoses(diagnoses.filter((_, i) => i !== index));
  }

  function updateDiagnosis(index: number, field: string, value: string) {
    const updated = [...diagnoses];
    (updated[index] as any)[field] = value;
    setDiagnoses(updated);
  }

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

    const form = new FormData(e.currentTarget);
    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 vital_signs: any = {};
    const vsFields = ["peso", "talla", "ta_sistolica", "ta_diastolica", "fc", "fr", "temp", "spo2"];
    for (const f of vsFields) {
      const v = form.get(f) as string;
      if (v) vital_signs[f] = parseFloat(v);
    }

    const { error: err } = await supabase.from("consultation_notes").insert({
      clinic_id: profile.clinic_id,
      patient_id: patientId,
      doctor_id: user.id,
      subjective: (form.get("subjective") as string) || null,
      objective: (form.get("objective") as string) || null,
      assessment: (form.get("assessment") as string) || null,
      plan: (form.get("plan") as string) || null,
      vital_signs: Object.keys(vital_signs).length > 0 ? vital_signs : null,
      diagnoses: diagnoses.filter(d => d.code && d.description),
    });

    if (err) { setError(err.message); setLoading(false); return; }
    router.push(`/medical-records/${patientId}`);
    router.refresh();
  }

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

      {/* Vital Signs */}
      <Card>
        <CardHeader><CardTitle className="text-base flex items-center gap-2"><Activity className="h-4 w-4 text-primary" /> Signos vitales</CardTitle></CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <div className="space-y-1"><Label className="text-xs">Peso (kg)</Label><Input name="peso" type="number" step="0.1" placeholder="70.0" className="h-9" /></div>
            <div className="space-y-1"><Label className="text-xs">Talla (cm)</Label><Input name="talla" type="number" step="0.1" placeholder="170" className="h-9" /></div>
            <div className="space-y-1"><Label className="text-xs">T/A Sistolica</Label><Input name="ta_sistolica" type="number" placeholder="120" className="h-9" /></div>
            <div className="space-y-1"><Label className="text-xs">T/A Diastolica</Label><Input name="ta_diastolica" type="number" placeholder="80" className="h-9" /></div>
            <div className="space-y-1"><Label className="text-xs">FC (lpm)</Label><Input name="fc" type="number" placeholder="72" className="h-9" /></div>
            <div className="space-y-1"><Label className="text-xs">FR (rpm)</Label><Input name="fr" type="number" placeholder="16" className="h-9" /></div>
            <div className="space-y-1"><Label className="text-xs">Temp (C)</Label><Input name="temp" type="number" step="0.1" placeholder="36.5" className="h-9" /></div>
            <div className="space-y-1"><Label className="text-xs">SpO2 (%)</Label><Input name="spo2" type="number" placeholder="98" className="h-9" /></div>
          </div>
        </CardContent>
      </Card>

      {/* SOAP Note */}
      <Card>
        <CardHeader><CardTitle className="text-base flex items-center gap-2"><Stethoscope className="h-4 w-4 text-primary" /> Nota SOAP</CardTitle></CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label className="font-semibold text-primary">S — Subjetivo</Label>
            <Textarea name="subjective" rows={3} placeholder="Lo que el paciente refiere: sintomas, motivo de consulta, cronologia..." />
          </div>
          <Separator />
          <div className="space-y-2">
            <Label className="font-semibold text-primary">O — Objetivo</Label>
            <Textarea name="objective" rows={3} placeholder="Hallazgos de exploracion fisica, resultados de estudios..." />
          </div>
          <Separator />
          <div className="space-y-2">
            <Label className="font-semibold text-primary">A — Evaluacion</Label>
            <Textarea name="assessment" rows={3} placeholder="Diagnostico o impresion clinica, analisis del caso..." />
          </div>
          <Separator />
          <div className="space-y-2">
            <Label className="font-semibold text-primary">P — Plan</Label>
            <Textarea name="plan" rows={3} placeholder="Plan de tratamiento, indicaciones, estudios a solicitar, proxima cita..." />
          </div>
        </CardContent>
      </Card>

      {/* Diagnoses */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle className="text-base">Diagnosticos (CIE-10)</CardTitle>
          <Button type="button" variant="outline" size="sm" onClick={addDiagnosis} className="gap-1"><Plus className="h-3 w-3" /> Agregar</Button>
        </CardHeader>
        <CardContent className="space-y-3">
          {diagnoses.length === 0 && <p className="text-sm text-muted-foreground">Sin diagnosticos. Haz clic en &quot;Agregar&quot; para anadir uno.</p>}
          {diagnoses.map((d, i) => (
            <div key={i} className="flex items-start gap-2">
              <Input placeholder="Codigo (ej: J06.9)" value={d.code} onChange={(e) => updateDiagnosis(i, "code", e.target.value)} className="h-9 w-[130px] font-mono" />
              <Input placeholder="Descripcion del diagnostico" value={d.description} onChange={(e) => updateDiagnosis(i, "description", e.target.value)} className="h-9 flex-1" />
              <Button type="button" variant="ghost" size="icon" className="h-9 w-9 text-muted-foreground hover:text-destructive" onClick={() => removeDiagnosis(i)}>
                <X className="h-4 w-4" />
              </Button>
            </div>
          ))}
        </CardContent>
      </Card>

      {/* Submit */}
      <div className="flex justify-end gap-3">
        <Button type="button" variant="ghost" onClick={() => router.back()}>Cancelar</Button>
        <Button type="submit" disabled={loading} className="gap-2 min-w-[160px]">
          {loading ? <><Loader2 className="h-4 w-4 animate-spin" /> Guardando...</> : <><Save className="h-4 w-4" /> Guardar consulta</>}
        </Button>
      </div>
    </form>
  );
}
