// app/manager/home/[id]/editar/page.tsx
"use client";

import React, { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { pacientesApi } from "@/services/pacientesApi";

interface Patient {
  id?: number | string;
  full_name?: string;
  [k: string]: any;
}

export default function ManagerHomeEditPage() {
  const params = useParams();
  const id = params?.id;
  const router = useRouter();

  const [patient, setPatient] = useState<Patient | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isSaving, setIsSaving] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let mounted = true;
    const load = async () => {
      setIsLoading(true);
      setError(null);
      try {
        if (!id) throw new Error("ID ausente");
        const data = await pacientesApi.getById(String(id));
        if (mounted) setPatient(data ?? null);
      } catch (err: any) {
        console.error("Erro ao buscar paciente:", err);
        if (mounted) setError(err?.message ?? "Erro ao buscar paciente");
      } finally {
        if (mounted) setIsLoading(false);
      }
    };
    load();
    return () => { mounted = false; };
  }, [id]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!id || !patient) return;
    setIsSaving(true);
    setError(null);
    try {
      await pacientesApi.update(String(id), patient);
      router.push("/manager/home");
    } catch (err: any) {
      console.error("Erro ao salvar paciente:", err);
      setError(err?.message ?? "Erro ao salvar");
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) return <div className="p-8">Carregando...</div>;
  if (error) return <div className="p-8 text-destructive">Erro: {error}</div>;
  if (!patient) return <div className="p-8">Paciente não encontrado.</div>;

  return (
    <main className="w-full p-4 md:p-8">
      <div className="max-w-screen-md mx-auto">
        <h1 className="text-2xl font-bold mb-4">Editar Paciente</h1>

        <form onSubmit={handleSubmit} className="space-y-4 bg-white p-6 border rounded">
          <div>
            <label className="block text-sm">Nome</label>
            <input value={patient.full_name ?? ""} onChange={(e) => setPatient({ ...patient, full_name: e.target.value })} required className="w-full" />
          </div>

          <div className="flex justify-end">
            <button type="button" onClick={() => router.push("/manager/home")} className="mr-2">Cancelar</button>
            <button type="submit" disabled={isSaving}>{isSaving ? "Salvando..." : "Salvar"}</button>
          </div>
        </form>
      </div>
    </main>
  );
}
