import React, { useState, useEffect } from "react";
import {
User, Mail, Phone, MapPin, DollarSign, Briefcase,
Camera, FileText, Check, CreditCard, Save, ChevronRight
} from "lucide-react";
import { Navbar } from "../components/Navbar";
import { Button } from "../components/Button";
import { useAuth } from "../contexts/AuthContext";
import { getFunctions } from "../services/apiService";
import { toast } from "react-hot-toast";
// --- Helper Components ---
interface InputFieldProps {
label: string;
icon?: any;
value?: any;
className?: string;
onChange?: (e: any) => void;
type?: string;
placeholder?: string;
maxLength?: number;
required?: boolean;
name?: string;
disabled?: boolean;
}
const InputField = ({ label, icon: Icon, className, ...props }: InputFieldProps) => (
);
const Toggle = ({ label, checked, onChange }: { label: string, checked: boolean, onChange: (val: boolean) => void }) => (
);
const SidebarItem = ({ id, label, icon: Icon, active, onClick }: any) => (
);
// --- Main Component ---
export const ProfilePage: React.FC = () => {
const { user, token } = useAuth();
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [activeTab, setActiveTab] = useState("personal");
const [functions, setFunctions] = useState([]);
// Form State
const [formData, setFormData] = useState({
id: "",
nome: "",
email: "",
whatsapp: "",
cpf_cnpj_titular: "",
endereco: "",
cidade: "",
uf: "",
banco: "",
agencia: "",
conta_pix: "",
carro_disponivel: false,
tem_estudio: false,
qtd_estudio: 0,
tipo_cartao: "",
equipamentos: "",
extra_por_equipamento: false,
funcoes_ids: [],
avatar_url: ""
});
// Fetch Data
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
try {
if (!token) return;
const response = await fetch(`${import.meta.env.VITE_API_URL || "http://localhost:8080"}/api/profissionais/me`, {
headers: { Authorization: `Bearer ${token}` }
});
if (!response.ok) {
if (response.status === 404) toast.error("Perfil profissional não encontrado.");
else throw new Error("Falha ao carregar perfil");
return;
}
const data = await response.json();
setFormData({
...data,
carro_disponivel: data.carro_disponivel || false,
tem_estudio: data.tem_estudio || false,
extra_por_equipamento: data.extra_por_equipamento || false,
qtd_estudio: data.qtd_estudio || 0,
funcoes_ids: data.functions ? data.functions.map((f: any) => f.id) : []
});
const funcsRes = await getFunctions();
if (funcsRes.data) setFunctions(funcsRes.data);
} catch (error) {
console.error(error);
toast.error("Erro ao carregar dados");
} finally {
setIsLoading(false);
}
};
fetchData();
}, [token]);
const handleChange = (field: string, value: any) => {
setFormData((prev: any) => ({ ...prev, [field]: value }));
};
const handleFunctionToggle = (funcId: string) => {
setFormData((prev: any) => {
const currentIds = prev.funcoes_ids || [];
return currentIds.includes(funcId)
? { ...prev, funcoes_ids: currentIds.filter((id: string) => id !== funcId) }
: { ...prev, funcoes_ids: [...currentIds, funcId] };
});
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSaving(true);
try {
if (!token) throw new Error("Usuário não autenticado");
const res = await fetch(`${import.meta.env.VITE_API_URL || "http://localhost:8080"}/api/profissionais/${formData.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(formData)
});
if (!res.ok) throw new Error("Erro ao salvar");
toast.success("Perfil atualizado!");
} catch (error) {
console.error(error);
toast.error("Erro ao salvar alterações");
} finally {
setIsSaving(false);
}
};
if (isLoading) {
return (
);
}
return (
window.location.href = `/${page}`} currentPage="profile" />
{/* Header */}
Meu Perfil
Gerencie suas informações pessoais e profissionais.
{/* Sidebar (Desktop) */}
{/* Mobile Tabs */}
{['personal', 'address', 'bank', 'equipment'].map(id => (
))}
{/* Content Area */}
);
};