"use client";

import { useState } from "react";
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 { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Loader2, Save, Building2, Receipt } from "lucide-react";
import { toast } from "sonner";

interface Props {
  clinic: any;
}

export function ClinicSettingsForm({ clinic }: Props) {
  const supabase = createClient();
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);
    const form = new FormData(e.currentTarget);

    const updates: Record<string, any> = {};
    const fields = ["name", "phone", "email", "address", "rfc", "razon_social", "regimen_fiscal", "codigo_postal"];
    for (const f of fields) updates[f] = (form.get(f) as string) || null;

    const { error } = await supabase.from("clinics").update(updates).eq("id", clinic?.id);
    setLoading(false);
    if (error) { toast.error("Error al guardar: " + error.message); return; }
    toast.success("Configuracion guardada");
  }

  return (
    <form onSubmit={handleSubmit}>
      <div className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2"><Building2 className="h-4 w-4 text-primary" /> Datos de la clinica</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2"><Label>Nombre de la clinica</Label><Input name="name" defaultValue={clinic?.name || ""} className="h-11" /></div>
              <div className="space-y-2"><Label>Telefono</Label><Input name="phone" defaultValue={clinic?.phone || ""} className="h-11" /></div>
            </div>
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2"><Label>Email</Label><Input name="email" type="email" defaultValue={clinic?.email || ""} className="h-11" /></div>
              <div className="space-y-2"><Label>Direccion</Label><Input name="address" defaultValue={clinic?.address || ""} className="h-11" /></div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2"><Receipt className="h-4 w-4 text-primary" /> Datos fiscales (CFDI)</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2"><Label>RFC</Label><Input name="rfc" defaultValue={clinic?.rfc || ""} className="h-11 font-mono uppercase" maxLength={13} placeholder="XAXX010101000" /></div>
              <div className="space-y-2"><Label>Razon social</Label><Input name="razon_social" defaultValue={clinic?.razon_social || ""} className="h-11" /></div>
            </div>
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label>Regimen fiscal</Label>
                <Select name="regimen_fiscal" defaultValue={clinic?.regimen_fiscal || ""}>
                  <SelectTrigger className="h-11"><SelectValue placeholder="Seleccionar" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="601">601 - General de Ley PM</SelectItem>
                    <SelectItem value="603">603 - Personas Morales sin fines de lucro</SelectItem>
                    <SelectItem value="612">612 - Personas Fisicas con Act. Empresarial</SelectItem>
                    <SelectItem value="621">621 - Incorporacion Fiscal</SelectItem>
                    <SelectItem value="626">626 - Regimen Simplificado de Confianza</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2"><Label>Codigo postal</Label><Input name="codigo_postal" defaultValue={clinic?.codigo_postal || ""} className="h-11" maxLength={5} placeholder="06600" /></div>
            </div>
          </CardContent>
        </Card>

        <div className="flex justify-end">
          <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 cambios</>}
          </Button>
        </div>
      </div>
    </form>
  );
}
