"use client";

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
    CheckCircleIcon,
    ClockIcon,
    UserCircleIcon,
    EnvelopeIcon,
    PhoneIcon,
    BuildingOfficeIcon,
    CalendarIcon,
    ChartBarIcon,
} from '@heroicons/react/24/outline';

interface Lead {
    id: string;
    name: string;
    email: string;
    phone: string;
    status: string;
    source: string;
    created_at: string;
}

interface CustomerData {
    customer: {
        id: string;
        name: string;
        email: string;
        phone: string;
        company: string;
        portal_last_login: string | null;
        portal_created_at: string;
        has_portal_access: boolean;
        is_active: boolean;
    };
    leads?: Lead[];
    stats?: {
        total_leads: number;
        active_leads: number;
        converted: number;
    };
}

export default function CustomerDashboardPage() {
    const router = useRouter();
    const [data, setData] = useState<CustomerData | null>(null);
    const [loading, setLoading] = useState(true);

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

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

            if (!response.ok) throw new Error('Erro ao buscar dados');

            const result = await response.json();
            setData(result);
        } catch (error) {
            console.error('Error fetching dashboard:', error);
        } finally {
            setLoading(false);
        }
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center h-full">
                <div className="text-center">
                    <svg className="animate-spin h-12 w-12 mx-auto text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <p className="mt-4 text-gray-600 dark:text-gray-400">Carregando...</p>
                </div>
            </div>
        );
    }

    const customer = data?.customer;
    const stats = data?.stats;
    const leads = data?.leads || [];
    const firstName = customer?.name?.split(' ')[0] || 'Cliente';

    const getStatusColor = (status: string) => {
        const colors: Record<string, string> = {
            novo: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300',
            qualificado: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
            negociacao: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300',
            convertido: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
            perdido: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
        };
        return colors[status] || 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-300';
    };

    return (
        <div className="p-6 max-w-[1600px] mx-auto space-y-8">
            {/* Header - Template Pattern */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                    <h1 className="text-2xl font-bold text-zinc-900 dark:text-white tracking-tight">
                        Olá, {firstName}! 👋
                    </h1>
                    <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
                        Bem-vindo ao seu portal. Acompanhe seus leads e o desempenho da sua conta.
                    </p>
                </div>
                <div className="flex gap-2">
                    <Link
                        href="/cliente/perfil"
                        className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-zinc-700 dark:text-zinc-200 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                    >
                        <UserCircleIcon className="w-4 h-4" />
                        Meu Perfil
                    </Link>
                    <Link
                        href="/cliente/leads"
                        className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg hover:opacity-90 transition-opacity"
                        style={{ background: 'var(--brand-color, #3B82F6)' }}
                    >
                        <ChartBarIcon className="w-4 h-4" />
                        Ver Todos os Leads
                    </Link>
                </div>
            </div>

            {/* Stats Cards */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="bg-white dark:bg-zinc-900 p-6 rounded-xl border border-zinc-200 dark:border-zinc-800 shadow-sm">
                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-xs font-medium text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Total de Leads</p>
                            <p className="text-3xl font-bold text-zinc-900 dark:text-white mt-1">{stats?.total_leads || 0}</p>
                        </div>
                        <div className="p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                            <ChartBarIcon className="w-6 h-6 text-blue-600 dark:text-blue-400" />
                        </div>
                    </div>
                </div>

                <div className="bg-white dark:bg-zinc-900 p-6 rounded-xl border border-zinc-200 dark:border-zinc-800 shadow-sm">
                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-xs font-medium text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Leads Convertidos</p>
                            <p className="text-3xl font-bold text-zinc-900 dark:text-white mt-1">{stats?.converted || 0}</p>
                        </div>
                        <div className="p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
                            <CheckCircleIcon className="w-6 h-6 text-green-600 dark:text-green-400" />
                        </div>
                    </div>
                </div>

                <div className="bg-white dark:bg-zinc-900 p-6 rounded-xl border border-zinc-200 dark:border-zinc-800 shadow-sm">
                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-xs font-medium text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Em Andamento</p>
                            <p className="text-3xl font-bold text-zinc-900 dark:text-white mt-1">{stats?.active_leads || 0}</p>
                        </div>
                        <div className="p-3 bg-purple-50 dark:bg-purple-900/20 rounded-lg">
                            <ClockIcon className="w-6 h-6 text-purple-600 dark:text-purple-400" />
                        </div>
                    </div>
                </div>
            </div>

            {/* Recent Leads List - Template Pattern */}
            <div className="bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden shadow-sm">
                <div className="px-6 py-4 border-b border-zinc-200 dark:border-zinc-800 flex items-center justify-between">
                    <h2 className="text-lg font-bold text-zinc-900 dark:text-white">Leads Recentes</h2>
                    <Link href="/cliente/leads" className="text-sm font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400">
                        Ver todos →
                    </Link>
                </div>
                <div className="overflow-x-auto">
                    <table className="w-full">
                        <thead>
                            <tr className="bg-zinc-50/50 dark:bg-zinc-800/50 border-b border-zinc-200 dark:border-zinc-800">
                                <th className="px-6 py-3 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Lead</th>
                                <th className="px-6 py-3 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Contato</th>
                                <th className="px-6 py-3 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Status</th>
                                <th className="px-6 py-3 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Data</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
                            {leads.length === 0 ? (
                                <tr>
                                    <td colSpan={4} className="px-6 py-12 text-center">
                                        <div className="flex flex-col items-center">
                                            <ChartBarIcon className="w-12 h-12 text-zinc-300 mb-3" />
                                            <p className="text-zinc-500 dark:text-zinc-400">Nenhum lead encontrado.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                leads.slice(0, 5).map((lead) => (
                                    <tr key={lead.id} className="hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors">
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <div className="flex items-center gap-3">
                                                <div className="w-8 h-8 rounded-full bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center text-zinc-600 dark:text-zinc-400 font-bold text-xs">
                                                    {lead.name.charAt(0).toUpperCase()}
                                                </div>
                                                <span className="text-sm font-medium text-zinc-900 dark:text-white">{lead.name}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <div className="flex flex-col">
                                                <span className="text-sm text-zinc-600 dark:text-zinc-400">{lead.email}</span>
                                                <span className="text-xs text-zinc-400">{lead.phone || 'Sem telefone'}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusColor(lead.status)}`}>
                                                {lead.status.charAt(0).toUpperCase() + lead.status.slice(1)}
                                            </span>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-zinc-500 dark:text-zinc-400">
                                            {new Date(lead.created_at).toLocaleDateString('pt-BR')}
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Quick Info Section */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div className="bg-white dark:bg-zinc-900 p-6 rounded-xl border border-zinc-200 dark:border-zinc-800 shadow-sm">
                    <h3 className="text-lg font-bold text-zinc-900 dark:text-white mb-4">Informações da Conta</h3>
                    <div className="space-y-4">
                        <div className="flex items-center justify-between py-2 border-b border-zinc-100 dark:border-zinc-800">
                            <span className="text-sm text-zinc-500">Empresa</span>
                            <span className="text-sm font-medium text-zinc-900 dark:text-white">{customer?.company}</span>
                        </div>
                        <div className="flex items-center justify-between py-2 border-b border-zinc-100 dark:border-zinc-800">
                            <span className="text-sm text-zinc-500">E-mail</span>
                            <span className="text-sm font-medium text-zinc-900 dark:text-white">{customer?.email}</span>
                        </div>
                        <div className="flex items-center justify-between py-2">
                            <span className="text-sm text-zinc-500">Status</span>
                            <span className="inline-flex items-center gap-1.5 text-sm font-medium text-green-600 dark:text-green-400">
                                <CheckCircleIcon className="w-4 h-4" />
                                Ativo
                            </span>
                        </div>
                    </div>
                </div>

                <div className="bg-white dark:bg-zinc-900 p-6 rounded-xl border border-zinc-200 dark:border-zinc-800 shadow-sm">
                    <h3 className="text-lg font-bold text-zinc-900 dark:text-white mb-4">Suporte e Ajuda</h3>
                    <p className="text-sm text-zinc-500 dark:text-zinc-400 mb-6">
                        Precisa de ajuda com seus leads ou tem alguma dúvida sobre o portal? Nossa equipe está à disposição.
                    </p>
                    <button className="w-full py-2.5 bg-zinc-100 dark:bg-zinc-800 text-zinc-900 dark:text-white rounded-lg text-sm font-medium hover:bg-zinc-200 dark:hover:bg-zinc-700 transition-colors">
                        Falar com Suporte
                    </button>
                </div>
            </div>
        </div>
    );
}
