"use client";

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import {
    ChartBarIcon,
    UsersIcon,
    FunnelIcon,
    ArrowTrendingUpIcon,
    ArrowTrendingDownIcon,
    EnvelopeIcon,
    PhoneIcon,
    TagIcon,
    UserPlusIcon,
} from '@heroicons/react/24/outline';

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

interface SharedData {
    customer: {
        name: string;
        company: string;
    };
    leads: Lead[];
    stats: {
        total: number;
        novo: number;
        qualificado: number;
        negociacao: number;
        convertido: number;
        perdido: number;
        bySource: Record<string, number>;
        conversionRate: number;
        thisMonth: number;
        lastMonth: number;
    };
}

const STATUS_OPTIONS = [
    { value: 'novo', label: 'Novo', color: 'bg-blue-100 text-blue-800' },
    { value: 'qualificado', label: 'Qualificado', color: 'bg-green-100 text-green-800' },
    { value: 'negociacao', label: 'Em Negociação', color: 'bg-yellow-100 text-yellow-800' },
    { value: 'convertido', label: 'Convertido', color: 'bg-purple-100 text-purple-800' },
    { value: 'perdido', label: 'Perdido', color: 'bg-red-100 text-red-800' },
];

export default function SharedLeadsPage() {
    const params = useParams();
    const token = params?.token as string;

    const [data, setData] = useState<SharedData | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        if (token) {
            fetchSharedData();
        }
    }, [token]);

    const fetchSharedData = async () => {
        try {
            const response = await fetch(`/api/crm/share/${token}`);

            if (!response.ok) {
                throw new Error('Link inválido ou expirado');
            }

            const result = await response.json();
            setData(result);
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Erro ao carregar dados');
        } finally {
            setLoading(false);
        }
    };

    const getStatusColor = (status: string) => {
        return STATUS_OPTIONS.find(s => s.value === status)?.color || 'bg-gray-100 text-gray-800';
    };

    if (loading) {
        return (
            <div className="min-h-screen bg-gray-50 flex items-center justify-center">
                <div className="text-center">
                    <div className="animate-spin w-12 h-12 border-4 border-brand-500 border-t-transparent rounded-full mx-auto mb-4"></div>
                    <p className="text-gray-600">Carregando dados...</p>
                </div>
            </div>
        );
    }

    if (error || !data) {
        return (
            <div className="min-h-screen bg-gray-50 flex items-center justify-center">
                <div className="text-center max-w-md mx-auto p-6">
                    <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <svg className="w-8 h-8 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </div>
                    <h1 className="text-2xl font-bold text-gray-900 mb-2">Link Inválido</h1>
                    <p className="text-gray-600">{error || 'Não foi possível acessar os dados compartilhados.'}</p>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gray-50">
            {/* Header */}
            <div className="bg-white border-b border-gray-200 shadow-sm">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
                    <div className="flex items-center justify-between">
                        <div>
                            <h1 className="text-3xl font-bold text-gray-900">
                                Dashboard de Leads
                            </h1>
                            <p className="text-sm text-gray-600 mt-1">
                                {data.customer.company || data.customer.name}
                            </p>
                        </div>
                        <div className="text-right text-sm text-gray-500">
                            <p>Atualizado em</p>
                            <p className="font-medium text-gray-900">{new Date().toLocaleDateString('pt-BR')}</p>
                        </div>
                    </div>
                </div>
            </div>

            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                {/* Cards de Métricas */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                    <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
                        <div className="flex items-center justify-between mb-2">
                            <h3 className="text-sm font-medium text-gray-600">Total de Leads</h3>
                            <UsersIcon className="w-5 h-5 text-brand-500" />
                        </div>
                        <p className="text-3xl font-bold text-gray-900">{data.stats.total}</p>
                        <div className="mt-2 flex items-center text-sm">
                            {data.stats.thisMonth >= data.stats.lastMonth ? (
                                <ArrowTrendingUpIcon className="w-4 h-4 text-green-500 mr-1" />
                            ) : (
                                <ArrowTrendingDownIcon className="w-4 h-4 text-red-500 mr-1" />
                            )}
                            <span className={data.stats.thisMonth >= data.stats.lastMonth ? 'text-green-600' : 'text-red-600'}>
                                {data.stats.thisMonth} este mês
                            </span>
                        </div>
                    </div>

                    <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
                        <div className="flex items-center justify-between mb-2">
                            <h3 className="text-sm font-medium text-gray-600">Taxa de Conversão</h3>
                            <FunnelIcon className="w-5 h-5 text-purple-500" />
                        </div>
                        <p className="text-3xl font-bold text-gray-900">
                            {data.stats.conversionRate.toFixed(1)}%
                        </p>
                        <p className="mt-2 text-sm text-gray-600">
                            {data.stats.convertido} convertidos
                        </p>
                    </div>

                    <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
                        <div className="flex items-center justify-between mb-2">
                            <h3 className="text-sm font-medium text-gray-600">Novos Leads</h3>
                            <UserPlusIcon className="w-5 h-5 text-blue-500" />
                        </div>
                        <p className="text-3xl font-bold text-gray-900">{data.stats.novo}</p>
                        <p className="mt-2 text-sm text-gray-600">
                            Aguardando qualificação
                        </p>
                    </div>

                    <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
                        <div className="flex items-center justify-between mb-2">
                            <h3 className="text-sm font-medium text-gray-600">Em Negociação</h3>
                            <TagIcon className="w-5 h-5 text-yellow-500" />
                        </div>
                        <p className="text-3xl font-bold text-gray-900">{data.stats.negociacao}</p>
                        <p className="mt-2 text-sm text-gray-600">
                            Potencial de conversão
                        </p>
                    </div>
                </div>

                {/* Distribuição por Status */}
                <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm mb-8">
                    <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                        <ChartBarIcon className="w-5 h-5" />
                        Distribuição por Status
                    </h3>
                    <div className="space-y-3">
                        {STATUS_OPTIONS.map(status => {
                            const count = data.stats[status.value as keyof typeof data.stats] as number || 0;
                            const percentage = data.stats.total > 0 ? (count / data.stats.total) * 100 : 0;
                            return (
                                <div key={status.value}>
                                    <div className="flex items-center justify-between mb-1">
                                        <span className="text-sm font-medium text-gray-700">
                                            {status.label}
                                        </span>
                                        <span className="text-sm text-gray-600">
                                            {count} ({percentage.toFixed(1)}%)
                                        </span>
                                    </div>
                                    <div className="w-full bg-gray-200 rounded-full h-2">
                                        <div
                                            className={`h-2 rounded-full ${status.color.split(' ')[0]}`}
                                            style={{ width: `${percentage}%` }}
                                        ></div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>

                {/* Leads por Origem */}
                <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm mb-8">
                    <h3 className="text-lg font-semibold text-gray-900 mb-4">
                        Leads por Origem
                    </h3>
                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                        {Object.entries(data.stats.bySource).map(([source, count]) => (
                            <div key={source} className="bg-gray-50 rounded-lg p-4">
                                <p className="text-sm text-gray-600 capitalize">{source}</p>
                                <p className="text-2xl font-bold text-gray-900 mt-1">{count}</p>
                            </div>
                        ))}
                    </div>
                </div>

                {/* Lista de Leads */}
                <div className="bg-white rounded-xl border border-gray-200 p-6 shadow-sm">
                    <h3 className="text-lg font-semibold text-gray-900 mb-4">
                        Todos os Leads ({data.leads.length})
                    </h3>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {data.leads.map((lead) => (
                            <div
                                key={lead.id}
                                className="bg-gray-50 rounded-lg border border-gray-200 p-4 hover:shadow-md transition-shadow"
                            >
                                <div className="flex items-start justify-between mb-3">
                                    <div className="flex-1 min-w-0">
                                        <h4 className="font-semibold text-gray-900 truncate">
                                            {lead.name || 'Sem nome'}
                                        </h4>
                                        <span className={`inline-block px-2 py-0.5 text-xs font-medium rounded-full mt-1 ${getStatusColor(lead.status)}`}>
                                            {STATUS_OPTIONS.find(s => s.value === lead.status)?.label || lead.status}
                                        </span>
                                    </div>
                                </div>

                                <div className="space-y-2 text-sm">
                                    {lead.email && (
                                        <div className="flex items-center gap-2 text-gray-600">
                                            <EnvelopeIcon className="w-4 h-4 flex-shrink-0" />
                                            <span className="truncate">{lead.email}</span>
                                        </div>
                                    )}
                                    {lead.phone && (
                                        <div className="flex items-center gap-2 text-gray-600">
                                            <PhoneIcon className="w-4 h-4 flex-shrink-0" />
                                            <span>{lead.phone}</span>
                                        </div>
                                    )}
                                    {lead.tags && lead.tags.length > 0 && (
                                        <div className="flex items-center gap-2 flex-wrap mt-2">
                                            {lead.tags.map((tag, idx) => (
                                                <span
                                                    key={idx}
                                                    className="inline-flex items-center gap-1 px-2 py-0.5 bg-gray-200 text-gray-700 text-xs rounded"
                                                >
                                                    <TagIcon className="w-3 h-3" />
                                                    {tag}
                                                </span>
                                            ))}
                                        </div>
                                    )}
                                </div>

                                <div className="mt-3 pt-3 border-t border-gray-300 text-xs text-gray-500">
                                    Origem: <span className="font-medium">{lead.source || 'manual'}</span>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                {/* Footer */}
                <div className="mt-8 text-center text-sm text-gray-500">
                    <p>Dados atualizados em tempo real</p>
                    <p className="mt-1">Powered by Aggios CRM</p>
                </div>
            </div>
        </div>
    );
}
