"use client";

import { useEffect, useState } from 'react';
import {
    ListBulletIcon,
    MagnifyingGlassIcon,
    UserGroupIcon,
} from '@heroicons/react/24/outline';

interface List {
    id: string;
    name: string;
    description: string;
    color: string;
    customer_count: number;
    created_at: string;
}

export default function CustomerListsPage() {
    const [lists, setLists] = useState<List[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');

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

    const fetchLists = async () => {
        try {
            const response = await fetch('/api/portal/lists', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                },
            });
            if (response.ok) {
                const data = await response.json();
                setLists(data.lists || []);
            }
        } catch (error) {
            console.error('Error fetching lists:', error);
        } finally {
            setLoading(false);
        }
    };

    const filteredLists = lists.filter(list =>
        list.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        list.description.toLowerCase().includes(searchTerm.toLowerCase())
    );

    return (
        <div className="p-6 space-y-6">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div>
                    <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Minhas Listas</h1>
                    <p className="text-gray-500 dark:text-gray-400">
                        Visualize as listas e segmentos onde seus leads estão organizados.
                    </p>
                </div>
            </div>

            {/* Filtros e Busca */}
            <div className="bg-white dark:bg-zinc-900 p-4 rounded-xl border border-gray-200 dark:border-zinc-800 shadow-sm">
                <div className="relative">
                    <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                    <input
                        type="text"
                        placeholder="Buscar listas..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="w-full pl-10 pr-4 py-2 bg-gray-50 dark:bg-zinc-800 border border-gray-200 dark:border-zinc-700 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none transition-all"
                    />
                </div>
            </div>

            {/* Grid de Listas */}
            {loading ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {[1, 2, 3].map((i) => (
                        <div key={i} className="h-48 bg-gray-100 dark:bg-zinc-800 animate-pulse rounded-xl" />
                    ))}
                </div>
            ) : filteredLists.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {filteredLists.map((list) => (
                        <div
                            key={list.id}
                            className="bg-white dark:bg-zinc-900 rounded-xl border border-gray-200 dark:border-zinc-800 shadow-sm hover:shadow-md transition-all overflow-hidden group"
                        >
                            <div
                                className="h-2 w-full"
                                style={{ backgroundColor: list.color || '#3B82F6' }}
                            />
                            <div className="p-5">
                                <div className="flex items-start justify-between mb-4">
                                    <div className="p-2 rounded-lg bg-gray-50 dark:bg-zinc-800 group-hover:scale-110 transition-transform">
                                        <ListBulletIcon
                                            className="w-6 h-6"
                                            style={{ color: list.color || '#3B82F6' }}
                                        />
                                    </div>
                                    <div className="flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 text-xs font-medium">
                                        <UserGroupIcon className="w-3.5 h-3.5" />
                                        {list.customer_count || 0} Leads
                                    </div>
                                </div>

                                <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-1 group-hover:text-blue-600 transition-colors">
                                    {list.name}
                                </h3>
                                <p className="text-sm text-gray-500 dark:text-gray-400 line-clamp-2 mb-4 h-10">
                                    {list.description || 'Sem descrição disponível.'}
                                </p>

                                <div className="pt-4 border-t border-gray-100 dark:border-zinc-800 flex items-center justify-between">
                                    <span className="text-xs text-gray-400">
                                        Criada em {new Date(list.created_at).toLocaleDateString('pt-BR')}
                                    </span>
                                    <button className="text-sm font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300">
                                        Ver Leads →
                                    </button>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            ) : (
                <div className="text-center py-20 bg-white dark:bg-zinc-900 rounded-xl border border-dashed border-gray-300 dark:border-zinc-700">
                    <ListBulletIcon className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                    <h3 className="text-lg font-medium text-gray-900 dark:text-white">Nenhuma lista encontrada</h3>
                    <p className="text-gray-500 dark:text-gray-400">
                        {searchTerm ? 'Tente ajustar sua busca.' : 'Você ainda não possui listas associadas aos seus leads.'}
                    </p>
                </div>
            )}
        </div>
    );
}
