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

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

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

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

  const [profile, setProfile] = useState<Profile | 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 full = await usuariosApi.getFullData(String(id));
        // getFullData pode retornar objeto com profile
        const prof = (full && full.profile) ? full.profile : full;
        if (mounted) setProfile(prof ?? null);
      } catch (err: any) {
        console.error("Erro ao buscar usuário:", err);
        if (mounted) setError(err?.message ?? "Erro ao buscar usuário");
      } finally {
        if (mounted) setIsLoading(false);
      }
    };
    load();
    return () => { mounted = false; };
  }, [id]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!id || !profile) return;
    setIsSaving(true);
    setError(null);
    try {
      await perfisApi.update(String(id), profile);
      router.push("/manager/usuario");
    } catch (err: any) {
      console.error("Erro ao atualizar perfil:", 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 (!profile) return <div className="p-8">Usuário 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 Usuário</h1>

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

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