'use client';

import { useEffect, useState } from 'react';
import {
    UserCircleIcon,
    EnvelopeIcon,
    PhoneIcon,
    BuildingOfficeIcon,
    KeyIcon,
    CalendarIcon,
    ChartBarIcon,
    ClockIcon,
    ShieldCheckIcon,
    ArrowPathIcon,
    CameraIcon,
    PhotoIcon
} from '@heroicons/react/24/outline';
import { Button, Input } from '@/components/ui';
import { useToast } from '@/components/layout/ToastContext';

interface CustomerProfile {
    id: string;
    name: string;
    email: string;
    phone: string;
    company: string;
    logo_url?: string;
    portal_last_login: string | null;
    created_at: string;
    total_leads: number;
    converted_leads: number;
}

export default function PerfilPage() {
    const toast = useToast();
    const [profile, setProfile] = useState<CustomerProfile | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [isChangingPassword, setIsChangingPassword] = useState(false);
    const [isUploadingLogo, setIsUploadingLogo] = useState(false);
    const [passwordForm, setPasswordForm] = useState({
        current_password: '',
        new_password: '',
        confirm_password: '',
    });
    const [passwordError, setPasswordError] = useState<string | null>(null);
    const [passwordSuccess, setPasswordSuccess] = useState(false);

    useEffect(() => {
        fetchProfile();
    }, []);

    const fetchProfile = async () => {
        try {
            const token = localStorage.getItem('token');
            const res = await fetch('/api/portal/profile', {
                headers: {
                    'Authorization': `Bearer ${token}`,
                },
            });

            if (!res.ok) throw new Error('Erro ao carregar perfil');

            const data = await res.json();
            setProfile(data.customer);
        } catch (error) {
            console.error('Erro ao carregar perfil:', error);
        } finally {
            setIsLoading(false);
        }
    };

    const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;

        // Validar tamanho (2MB)
        if (file.size > 2 * 1024 * 1024) {
            toast.error('Arquivo muito grande', 'O logo deve ter no máximo 2MB.');
            return;
        }

        const formData = new FormData();
        formData.append('logo', file);

        setIsUploadingLogo(true);
        try {
            const token = localStorage.getItem('token');
            const res = await fetch('/api/portal/logo', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                },
                body: formData,
            });

            if (!res.ok) throw new Error('Erro ao fazer upload do logo');

            const data = await res.json();
            setProfile(prev => prev ? { ...prev, logo_url: data.logo_url } : null);
            toast.success('Logo atualizado', 'Seu logo foi atualizado com sucesso.');
        } catch (error) {
            console.error('Error uploading logo:', error);
            toast.error('Erro no upload', 'Não foi possível atualizar seu logo.');
        } finally {
            setIsUploadingLogo(false);
        }
    };

    const handlePasswordChange = async (e: React.FormEvent) => {
        e.preventDefault();
        setPasswordError(null);
        setPasswordSuccess(false);

        if (passwordForm.new_password !== passwordForm.confirm_password) {
            setPasswordError('As senhas não coincidem');
            return;
        }

        if (passwordForm.new_password.length < 6) {
            setPasswordError('A nova senha deve ter no mínimo 6 caracteres');
            return;
        }

        setIsChangingPassword(true);
        try {
            const token = localStorage.getItem('token');
            const res = await fetch('/api/portal/change-password', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`,
                },
                body: JSON.stringify({
                    current_password: passwordForm.current_password,
                    new_password: passwordForm.new_password,
                }),
            });

            const data = await res.json();
            if (!res.ok) throw new Error(data.error || 'Erro ao alterar senha');

            setPasswordSuccess(true);
            setPasswordForm({
                current_password: '',
                new_password: '',
                confirm_password: '',
            });
        } catch (error: any) {
            setPasswordError(error.message);
        } finally {
            setIsChangingPassword(false);
        }
    };

    if (isLoading) {
        return (
            <div className="flex items-center justify-center h-[60vh]">
                <div className="text-center">
                    <ArrowPathIcon className="w-10 h-10 animate-spin mx-auto text-brand-500" />
                    <p className="mt-4 text-gray-500 dark:text-zinc-400">Carregando seu perfil...</p>
                </div>
            </div>
        );
    }

    if (!profile) {
        return (
            <div className="flex flex-col items-center justify-center h-[60vh] text-center px-4">
                <div className="w-16 h-16 bg-red-100 dark:bg-red-900/20 rounded-full flex items-center justify-center mb-4">
                    <UserCircleIcon className="w-10 h-10 text-red-600 dark:text-red-400" />
                </div>
                <h2 className="text-xl font-bold text-gray-900 dark:text-white">Ops! Algo deu errado</h2>
                <p className="mt-2 text-gray-500 dark:text-zinc-400 max-w-xs">
                    Não conseguimos carregar suas informações. Por favor, tente novamente mais tarde.
                </p>
                <Button onClick={fetchProfile} className="mt-6">
                    Tentar Novamente
                </Button>
            </div>
        );
    }

    return (
        <div className="p-6 lg:p-8 max-w-5xl mx-auto">
            {/* Header */}
            <div className="mb-8">
                <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Meu Perfil</h1>
                <p className="text-gray-500 dark:text-zinc-400 mt-1">
                    Gerencie suas informações pessoais e segurança da conta.
                </p>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                {/* Coluna da Esquerda: Info do Usuário */}
                <div className="lg:col-span-2 space-y-6">
                    {/* Card de Informações Básicas */}
                    <div className="bg-white dark:bg-zinc-900 rounded-2xl border border-gray-200 dark:border-zinc-800 overflow-hidden shadow-sm">
                        <div className="h-32 bg-gradient-to-r from-brand-500/20 to-brand-600/20 dark:from-brand-500/10 dark:to-brand-600/10 relative">
                            <div className="absolute -bottom-12 left-8">
                                <div className="relative group">
                                    <div className="w-24 h-24 rounded-2xl bg-white dark:bg-zinc-800 border-4 border-white dark:border-zinc-900 shadow-xl flex items-center justify-center overflow-hidden">
                                        {profile.logo_url ? (
                                            <img src={profile.logo_url} alt={profile.name} className="w-full h-full object-contain p-2" />
                                        ) : (
                                            <UserCircleIcon className="w-16 h-16 text-gray-300 dark:text-zinc-600" />
                                        )}

                                        {isUploadingLogo && (
                                            <div className="absolute inset-0 bg-black/40 flex items-center justify-center">
                                                <ArrowPathIcon className="w-8 h-8 text-white animate-spin" />
                                            </div>
                                        )}
                                    </div>

                                    <label className="absolute -bottom-2 -right-2 w-8 h-8 bg-brand-500 hover:bg-brand-600 text-white rounded-full flex items-center justify-center cursor-pointer shadow-lg transition-all transform group-hover:scale-110">
                                        <CameraIcon className="w-4 h-4" />
                                        <input
                                            type="file"
                                            className="hidden"
                                            accept="image/png,image/jpeg,image/jpg,image/svg+xml"
                                            onChange={handleLogoUpload}
                                            disabled={isUploadingLogo}
                                        />
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div className="pt-16 pb-8 px-8">
                            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
                                <div>
                                    <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{profile.name}</h2>
                                    <p className="text-brand-600 dark:text-brand-400 font-medium">{profile.company || 'Cliente Aggios'}</p>
                                </div>
                                <div className="flex items-center gap-2 px-3 py-1 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 rounded-full text-sm font-medium self-start">
                                    <ShieldCheckIcon className="w-4 h-4" />
                                    Conta Ativa
                                </div>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div className="space-y-4">
                                    <div className="flex items-center gap-3 text-gray-600 dark:text-zinc-400">
                                        <EnvelopeIcon className="w-5 h-5 text-gray-400" />
                                        <div>
                                            <p className="text-xs font-medium text-gray-400 uppercase tracking-wider">E-mail</p>
                                            <p className="text-gray-900 dark:text-white">{profile.email}</p>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-3 text-gray-600 dark:text-zinc-400">
                                        <PhoneIcon className="w-5 h-5 text-gray-400" />
                                        <div>
                                            <p className="text-xs font-medium text-gray-400 uppercase tracking-wider">Telefone</p>
                                            <p className="text-gray-900 dark:text-white">{profile.phone || 'Não informado'}</p>
                                        </div>
                                    </div>
                                </div>
                                <div className="space-y-4">
                                    <div className="flex items-center gap-3 text-gray-600 dark:text-zinc-400">
                                        <CalendarIcon className="w-5 h-5 text-gray-400" />
                                        <div>
                                            <p className="text-xs font-medium text-gray-400 uppercase tracking-wider">Membro desde</p>
                                            <p className="text-gray-900 dark:text-white">
                                                {new Date(profile.created_at).toLocaleDateString('pt-BR', { day: '2-digit', month: 'long', year: 'numeric' })}
                                            </p>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-3 text-gray-600 dark:text-zinc-400">
                                        <ClockIcon className="w-5 h-5 text-gray-400" />
                                        <div>
                                            <p className="text-xs font-medium text-gray-400 uppercase tracking-wider">Último Acesso</p>
                                            <p className="text-gray-900 dark:text-white">
                                                {profile.portal_last_login
                                                    ? new Date(profile.portal_last_login).toLocaleString('pt-BR')
                                                    : 'Primeiro acesso'}
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Card de Estatísticas Rápidas */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div className="bg-white dark:bg-zinc-900 p-6 rounded-2xl border border-gray-200 dark:border-zinc-800 shadow-sm">
                            <div className="flex items-center gap-4">
                                <div className="w-12 h-12 bg-brand-100 dark:bg-brand-900/20 rounded-xl flex items-center justify-center">
                                    <ChartBarIcon className="w-6 h-6 text-brand-600 dark:text-brand-400" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-500 dark:text-zinc-400">Total de Leads</p>
                                    <p className="text-2xl font-bold text-gray-900 dark:text-white">{profile.total_leads}</p>
                                </div>
                            </div>
                        </div>
                        <div className="bg-white dark:bg-zinc-900 p-6 rounded-2xl border border-gray-200 dark:border-zinc-800 shadow-sm">
                            <div className="flex items-center gap-4">
                                <div className="w-12 h-12 bg-green-100 dark:bg-green-900/20 rounded-xl flex items-center justify-center">
                                    <ShieldCheckIcon className="w-6 h-6 text-green-600 dark:text-green-400" />
                                </div>
                                <div>
                                    <p className="text-sm text-gray-500 dark:text-zinc-400">Leads Convertidos</p>
                                    <p className="text-2xl font-bold text-gray-900 dark:text-white">{profile.converted_leads}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Coluna da Direita: Segurança */}
                <div className="space-y-6">
                    <div className="bg-white dark:bg-zinc-900 p-6 rounded-2xl border border-gray-200 dark:border-zinc-800 shadow-sm">
                        <div className="flex items-center gap-3 mb-6">
                            <div className="w-10 h-10 bg-amber-100 dark:bg-amber-900/20 rounded-lg flex items-center justify-center">
                                <KeyIcon className="w-5 h-5 text-amber-600 dark:text-amber-400" />
                            </div>
                            <h3 className="text-lg font-bold text-gray-900 dark:text-white">Segurança</h3>
                        </div>

                        <form onSubmit={handlePasswordChange} className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 dark:text-zinc-300 mb-1.5">
                                    Senha Atual
                                </label>
                                <Input
                                    type="password"
                                    placeholder="••••••••"
                                    value={passwordForm.current_password}
                                    onChange={(e) => setPasswordForm({ ...passwordForm, current_password: e.target.value })}
                                    required
                                />
                            </div>

                            <div className="h-px bg-gray-100 dark:bg-zinc-800 my-2" />

                            <div>
                                <label className="block text-sm font-medium text-gray-700 dark:text-zinc-300 mb-1.5">
                                    Nova Senha
                                </label>
                                <Input
                                    type="password"
                                    placeholder="Mínimo 6 caracteres"
                                    value={passwordForm.new_password}
                                    onChange={(e) => setPasswordForm({ ...passwordForm, new_password: e.target.value })}
                                    required
                                    minLength={6}
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 dark:text-zinc-300 mb-1.5">
                                    Confirmar Nova Senha
                                </label>
                                <Input
                                    type="password"
                                    placeholder="Repita a nova senha"
                                    value={passwordForm.confirm_password}
                                    onChange={(e) => setPasswordForm({ ...passwordForm, confirm_password: e.target.value })}
                                    required
                                    minLength={6}
                                />
                            </div>

                            {passwordError && (
                                <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 rounded-xl text-red-600 dark:text-red-400 text-sm">
                                    {passwordError}
                                </div>
                            )}

                            {passwordSuccess && (
                                <div className="p-3 bg-green-50 dark:bg-green-900/20 border border-green-100 dark:border-green-900/30 rounded-xl text-green-600 dark:text-green-400 text-sm">
                                    Senha alterada com sucesso!
                                </div>
                            )}

                            <Button
                                type="submit"
                                className="w-full"
                                isLoading={isChangingPassword}
                            >
                                Atualizar Senha
                            </Button>
                        </form>
                    </div>

                    <div className="bg-brand-50 dark:bg-brand-900/10 p-6 rounded-2xl border border-brand-100 dark:border-brand-900/20">
                        <h4 className="text-brand-900 dark:text-brand-300 font-bold mb-2">Precisa de ajuda?</h4>
                        <p className="text-brand-700 dark:text-brand-400 text-sm mb-4">
                            Se você tiver problemas com sua conta ou precisar alterar dados cadastrais, entre em contato com o suporte da agência.
                        </p>
                        <a
                            href="mailto:suporte@aggios.app"
                            className="text-brand-600 dark:text-brand-400 text-sm font-bold hover:underline"
                        >
                            suporte@aggios.app
                        </a>
                    </div>
                </div>
            </div>
        </div>
    );
}

