"use client";

import { Fragment, useEffect, useState } from 'react';
import { Menu, Listbox, Transition } from '@headlessui/react';
import CreatePlanModal from '@/components/plans/CreatePlanModal';
import EditPlanModal from '@/components/plans/EditPlanModal';
import ConfirmDialog from '@/components/layout/ConfirmDialog';
import Pagination from '@/components/layout/Pagination';
import { useToast } from '@/components/layout/ToastContext';
import {
    SparklesIcon,
    TrashIcon,
    PencilIcon,
    EllipsisVerticalIcon,
    MagnifyingGlassIcon,
    CheckIcon,
    ChevronUpDownIcon,
    PlusIcon,
    XMarkIcon
} from '@heroicons/react/24/outline';

interface Plan {
    id: string;
    name: string;
    description?: string;
    monthly_price?: string;
    annual_price?: string;
    min_users: number;
    max_users: number;
    storage_gb: number;
    is_active: boolean;
    features?: string[];
    differentiators?: string[];
    solutions_count?: number;
}

const STATUS_OPTIONS = [
    { id: 'all', name: 'Todos os Status' },
    { id: 'active', name: 'Ativos' },
    { id: 'inactive', name: 'Inativos' },
];

export default function PlansPage() {
    const toast = useToast();
    const [plans, setPlans] = useState<Plan[]>([]);
    const [loading, setLoading] = useState(true);
    const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [editingPlanId, setEditingPlanId] = useState<string | null>(null);

    const [confirmOpen, setConfirmOpen] = useState(false);
    const [planToDelete, setPlanToDelete] = useState<string | null>(null);
    const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

    const [currentPage, setCurrentPage] = useState(1);
    const itemsPerPage = 10;

    const [searchTerm, setSearchTerm] = useState('');
    const [selectedStatus, setSelectedStatus] = useState(STATUS_OPTIONS[0]);

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

    const fetchPlans = async () => {
        try {
            const response = await fetch('/api/admin/plans', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                },
            });
            if (response.ok) {
                const data = await response.json();
                const plansData = data.plans || [];

                // Buscar contagem de soluções para cada plano
                const plansWithSolutions = await Promise.all(
                    plansData.map(async (plan: Plan) => {
                        try {
                            const solResponse = await fetch(`/api/admin/plans/${plan.id}/solutions`, {
                                headers: {
                                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                                },
                            });
                            if (solResponse.ok) {
                                const solData = await solResponse.json();
                                return { ...plan, solutions_count: solData.solutions?.length || 0 };
                            }
                        } catch (e) {
                            console.error('Erro ao buscar soluções do plano:', e);
                        }
                        return { ...plan, solutions_count: 0 };
                    })
                );

                setPlans(plansWithSolutions);
            }
        } catch (error) {
            console.error('Error fetching plans:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleDeleteClick = (id: string) => {
        setPlanToDelete(id);
        setConfirmOpen(true);
    };

    const handleConfirmDelete = async () => {
        if (!planToDelete) return;

        try {
            const response = await fetch(`/api/admin/plans/${planToDelete}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                },
            });

            if (response.ok) {
                setPlans(plans.filter(p => p.id !== planToDelete));
                selectedIds.delete(planToDelete);
                setSelectedIds(new Set(selectedIds));
                toast.success('Plano excluído', 'O plano foi excluído com sucesso.');
            } else {
                toast.error('Erro ao excluir', 'Não foi possível excluir o plano.');
            }
        } catch (error) {
            console.error('Error deleting plan:', error);
            toast.error('Erro ao excluir', 'Ocorreu um erro ao excluir o plano.');
        } finally {
            setConfirmOpen(false);
            setPlanToDelete(null);
        }
    };

    const handleDeleteSelected = () => {
        if (selectedIds.size === 0) return;
        setPlanToDelete('multiple');
        setConfirmOpen(true);
    };

    const handleConfirmDeleteMultiple = async () => {
        const idsToDelete = Array.from(selectedIds);
        let successCount = 0;

        for (const id of idsToDelete) {
            try {
                const response = await fetch(`/api/admin/plans/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    },
                });
                if (response.ok) successCount++;
            } catch (error) {
                console.error('Error deleting plan:', error);
            }
        }

        setPlans(plans.filter(p => !selectedIds.has(p.id)));
        setSelectedIds(new Set());
        toast.success(`${successCount} plano(s) excluído(s)`, 'Os planos selecionados foram excluídos.');
        setConfirmOpen(false);
        setPlanToDelete(null);
    };

    const toggleActive = async (id: string, currentStatus: boolean) => {
        try {
            const response = await fetch(`/api/admin/plans/${id}`, {
                method: 'PATCH',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ is_active: !currentStatus }),
            });

            if (response.ok) {
                setPlans(plans.map(p =>
                    p.id === id ? { ...p, is_active: !currentStatus } : p
                ));
            }
        } catch (error) {
            console.error('Error toggling plan status:', error);
        }
    };

    const clearFilters = () => {
        setSearchTerm('');
        setSelectedStatus(STATUS_OPTIONS[0]);
    };

    const handleEdit = (planId: string) => {
        setEditingPlanId(planId);
        setIsEditModalOpen(true);
    };

    const handleEditSuccess = () => {
        fetchPlans();
        toast.success('Plano atualizado', 'O plano foi atualizado com sucesso.');
    };

    // Lógica de Filtragem
    const filteredPlans = plans.filter((plan) => {
        // Texto
        const searchLower = searchTerm.toLowerCase();
        const matchesSearch =
            (plan.name?.toLowerCase() || '').includes(searchLower) ||
            (plan.description?.toLowerCase() || '').includes(searchLower);

        // Status
        const matchesStatus =
            selectedStatus.id === 'all' ? true :
                selectedStatus.id === 'active' ? plan.is_active :
                    !plan.is_active;

        return matchesSearch && matchesStatus;
    });

    // Paginação
    const totalItems = filteredPlans.length;
    const totalPages = Math.ceil(totalItems / itemsPerPage);
    const paginatedPlans = filteredPlans.slice(
        (currentPage - 1) * itemsPerPage,
        currentPage * itemsPerPage
    );

    // Seleção múltipla
    const toggleSelectAll = () => {
        if (selectedIds.size === paginatedPlans.length) {
            setSelectedIds(new Set());
        } else {
            setSelectedIds(new Set(paginatedPlans.map(p => p.id)));
        }
    };

    const toggleSelect = (id: string) => {
        const newSelected = new Set(selectedIds);
        if (newSelected.has(id)) {
            newSelected.delete(id);
        } else {
            newSelected.add(id);
        }
        setSelectedIds(newSelected);
    };

    return (
        <div className="p-6 max-w-[1600px] mx-auto space-y-6">
            {/* Header */}
            <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">Planos</h1>
                    <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
                        Gerencie os planos de assinatura da plataforma.
                    </p>
                </div>
                <div className="flex items-center gap-2">
                    {selectedIds.size > 0 && (
                        <button
                            onClick={handleDeleteSelected}
                            className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors"
                        >
                            <TrashIcon className="w-4 h-4" />
                            Excluir ({selectedIds.size})
                        </button>
                    )}
                    <button
                        onClick={() => setIsCreateModalOpen(true)}
                        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(--gradient)' }}
                    >
                        <PlusIcon className="w-4 h-4" />
                        Novo Plano
                    </button>
                </div>
            </div>

            {/* Toolbar de Filtros */}
            <div className="flex flex-col lg:flex-row gap-4 items-center justify-between">
                {/* Busca */}
                <div className="relative w-full lg:w-96">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <MagnifyingGlassIcon className="h-5 w-5 text-zinc-400" aria-hidden="true" />
                    </div>
                    <input
                        type="text"
                        className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg leading-5 bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:ring-1 focus:ring-[var(--brand-color)] focus:border-[var(--brand-color)] sm:text-sm transition duration-150 ease-in-out"
                        placeholder="Buscar por nome, email ou subdomínio..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                    />
                </div>

                <div className="flex flex-col sm:flex-row gap-3 w-full lg:w-auto">
                    {/* Filtro de Status */}
                    <Listbox value={selectedStatus} onChange={setSelectedStatus}>
                        <div className="relative w-full sm:w-[180px]">
                            <Listbox.Button className="relative w-full cursor-pointer rounded-lg bg-white dark:bg-zinc-900 py-2 pl-3 pr-10 text-left text-sm border border-zinc-200 dark:border-zinc-700 focus:outline-none focus:border-[var(--brand-color)] focus:ring-1 focus:ring-[var(--brand-color)] text-zinc-700 dark:text-zinc-300">
                                <span className="block truncate">{selectedStatus.name}</span>
                                <span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                                    <ChevronUpDownIcon className="h-4 w-4 text-zinc-400" aria-hidden="true" />
                                </span>
                            </Listbox.Button>
                            <Transition
                                as={Fragment}
                                leave="transition ease-in duration-100"
                                leaveFrom="opacity-100"
                                leaveTo="opacity-0"
                            >
                                <Listbox.Options className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white dark:bg-zinc-800 py-1 text-base ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm border border-zinc-200 dark:border-zinc-700">
                                    {STATUS_OPTIONS.map((status, statusIdx) => (
                                        <Listbox.Option
                                            key={statusIdx}
                                            className={({ active, selected }) =>
                                                `relative cursor-default select-none py-2 pl-10 pr-4 ${active ? 'bg-zinc-100 dark:bg-zinc-700 text-zinc-900 dark:text-white' : 'text-zinc-900 dark:text-zinc-100'
                                                }`
                                            }
                                            value={status}
                                        >
                                            {({ selected }) => (
                                                <>
                                                    <span className={`block truncate ${selected ? 'font-medium' : 'font-normal'}`}>
                                                        {status.name}
                                                    </span>
                                                    {selected ? (
                                                        <span className="absolute inset-y-0 left-0 flex items-center pl-3 text-[var(--brand-color)]">
                                                            <CheckIcon className="h-4 w-4" aria-hidden="true" />
                                                        </span>
                                                    ) : null}
                                                </>
                                            )}
                                        </Listbox.Option>
                                    ))}
                                </Listbox.Options>
                            </Transition>
                        </div>
                    </Listbox>

                    {/* Botão Limpar */}
                    {(searchTerm || selectedStatus.id !== 'all') && (
                        <button
                            onClick={clearFilters}
                            className="inline-flex items-center justify-center px-3 py-2 border border-zinc-200 dark:border-zinc-700 text-sm font-medium rounded-lg text-zinc-700 dark:text-zinc-200 bg-white dark:bg-zinc-900 hover:bg-zinc-50 dark:hover:bg-zinc-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--brand-color)]"
                            title="Limpar Filtros"
                        >
                            <XMarkIcon className="h-4 w-4" />
                        </button>
                    )}
                </div>
            </div>

            {/* Tabela */}
            {loading ? (
                <div className="flex items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
                </div>
            ) : filteredPlans.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 text-center p-8">
                    <div className="w-16 h-16 bg-zinc-50 dark:bg-zinc-800 rounded-full flex items-center justify-center mb-4">
                        <SparklesIcon className="w-8 h-8 text-zinc-400" />
                    </div>
                    <h3 className="text-lg font-medium text-zinc-900 dark:text-white mb-1">
                        Nenhum plano encontrado
                    </h3>
                    <p className="text-zinc-500 dark:text-zinc-400 max-w-sm mx-auto">
                        Não encontramos resultados para os filtros selecionados. Tente limpar a busca ou alterar os filtros.
                    </p>
                    <button
                        onClick={clearFilters}
                        className="mt-4 text-sm text-[var(--brand-color)] hover:underline font-medium"
                    >
                        Limpar todos os filtros
                    </button>
                </div>
            ) : (
                <div className="bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden">
                    <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-4 w-12">
                                        <input
                                            type="checkbox"
                                            checked={selectedIds.size === paginatedPlans.length && paginatedPlans.length > 0}
                                            onChange={toggleSelectAll}
                                            className="w-4 h-4 text-[var(--brand-color)] bg-zinc-100 border-zinc-300 rounded focus:ring-[var(--brand-color)] dark:focus:ring-[var(--brand-color)] dark:ring-offset-zinc-900 focus:ring-2 dark:bg-zinc-700 dark:border-zinc-600"
                                        />
                                    </th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Plano</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Preços</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Usuários</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Armazenamento</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Soluções</th>
                                    <th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Status</th>
                                    <th className="px-6 py-4 text-right text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Ações</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
                                {paginatedPlans.map((plan) => (
                                    <tr key={plan.id} className="group hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors cursor-pointer" onClick={() => handleEdit(plan.id)}>
                                        <td className="px-6 py-4 w-12" onClick={(e) => e.stopPropagation()}>
                                            <input
                                                type="checkbox"
                                                checked={selectedIds.has(plan.id)}
                                                onChange={() => toggleSelect(plan.id)}
                                                className="w-4 h-4 text-[var(--brand-color)] bg-zinc-100 border-zinc-300 rounded focus:ring-[var(--brand-color)] dark:focus:ring-[var(--brand-color)] dark:ring-offset-zinc-900 focus:ring-2 dark:bg-zinc-700 dark:border-zinc-600"
                                            />
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <div className="flex items-center gap-4">
                                                <div
                                                    className="w-10 h-10 rounded-lg flex items-center justify-center text-white font-bold text-sm"
                                                    style={{ background: 'var(--gradient)' }}
                                                >
                                                    {plan.name?.substring(0, 2).toUpperCase()}
                                                </div>
                                                <div>
                                                    <div className="text-sm font-semibold text-zinc-900 dark:text-white">
                                                        {plan.name}
                                                    </div>
                                                    {plan.description && (
                                                        <div className="text-xs text-zinc-500">
                                                            {plan.description}
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <div className="flex flex-col gap-0.5">
                                                <span className="text-sm text-zinc-700 dark:text-zinc-300">
                                                    {plan.monthly_price ? `R$ ${plan.monthly_price}/mês` : '-'}
                                                </span>
                                                <span className="text-xs text-zinc-400">
                                                    {plan.annual_price ? `R$ ${plan.annual_price}/ano` : '-'}
                                                </span>
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-zinc-700 dark:text-zinc-300">
                                            {plan.min_users} - {plan.max_users}
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-zinc-700 dark:text-zinc-300">
                                            {plan.storage_gb} GB
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300 border border-zinc-200 dark:border-zinc-700">
                                                <span className="w-1.5 h-1.5 rounded-full bg-[var(--brand-color)]" />
                                                {plan.solutions_count || 0} {plan.solutions_count === 1 ? 'solução' : 'soluções'}
                                            </span>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap" onClick={(e) => e.stopPropagation()}>
                                            <button
                                                onClick={() => toggleActive(plan.id, plan.is_active)}
                                                className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${plan.is_active
                                                    ? 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-900/30'
                                                    : 'bg-zinc-100 text-zinc-600 border-zinc-200 dark:bg-zinc-800 dark:text-zinc-400 dark:border-zinc-700'
                                                    }`}
                                            >
                                                <span className={`w-1.5 h-1.5 rounded-full ${plan.is_active ? 'bg-emerald-500' : 'bg-zinc-400'}`} />
                                                {plan.is_active ? 'Ativo' : 'Inativo'}
                                            </button>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap text-right" onClick={(e) => e.stopPropagation()}>
                                            <Menu as="div" className="relative inline-block text-left">
                                                <Menu.Button className="p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors outline-none">
                                                    <EllipsisVerticalIcon className="w-5 h-5" />
                                                </Menu.Button>
                                                <Menu.Items
                                                    transition
                                                    portal
                                                    anchor="bottom end"
                                                    className="w-48 origin-top-right divide-y divide-zinc-100 dark:divide-zinc-800 rounded-xl bg-white dark:bg-zinc-900 focus:outline-none z-50 border border-zinc-200 dark:border-zinc-800 [--anchor-gap:8px] transition duration-100 ease-out data-[closed]:scale-95 data-[closed]:opacity-0"
                                                >
                                                    <div className="px-1 py-1">
                                                        <Menu.Item>
                                                            {({ active }) => (
                                                                <button
                                                                    onClick={() => handleEdit(plan.id)}
                                                                    className={`${active ? 'bg-zinc-50 dark:bg-zinc-800' : ''
                                                                        } group flex w-full items-center rounded-lg px-2 py-2 text-sm text-zinc-700 dark:text-zinc-300`}
                                                                >
                                                                    <PencilIcon className="mr-2 h-4 w-4 text-zinc-400" />
                                                                    Editar
                                                                </button>
                                                            )}
                                                        </Menu.Item>
                                                    </div>
                                                    <div className="px-1 py-1">
                                                        <Menu.Item>
                                                            {({ active }) => (
                                                                <button
                                                                    onClick={() => handleDeleteClick(plan.id)}
                                                                    className={`${active ? 'bg-red-50 dark:bg-red-900/20' : ''
                                                                        } group flex w-full items-center rounded-lg px-2 py-2 text-sm text-red-600 dark:text-red-400`}
                                                                >
                                                                    <TrashIcon className="mr-2 h-4 w-4" />
                                                                    Excluir
                                                                </button>
                                                            )}
                                                        </Menu.Item>
                                                    </div>
                                                </Menu.Items>
                                            </Menu>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>

                    <Pagination
                        currentPage={currentPage}
                        totalPages={totalPages}
                        totalItems={totalItems}
                        itemsPerPage={itemsPerPage}
                        onPageChange={setCurrentPage}
                    />
                </div>
            )}

            <CreatePlanModal
                isOpen={isCreateModalOpen}
                onClose={() => setIsCreateModalOpen(false)}
                onSuccess={(plan) => {
                    setPlans([...plans, plan]);
                    setIsCreateModalOpen(false);
                }}
            />

            <EditPlanModal
                isOpen={isEditModalOpen}
                onClose={() => {
                    setIsEditModalOpen(false);
                    setEditingPlanId(null);
                }}
                planId={editingPlanId}
                onSuccess={handleEditSuccess}
            />

            <ConfirmDialog
                isOpen={confirmOpen}
                onClose={() => {
                    setConfirmOpen(false);
                    setPlanToDelete(null);
                }}
                onConfirm={planToDelete === 'multiple' ? handleConfirmDeleteMultiple : handleConfirmDelete}
                title={planToDelete === 'multiple' ? 'Excluir Planos' : 'Excluir Plano'}
                message={
                    planToDelete === 'multiple'
                        ? `Tem certeza que deseja excluir ${selectedIds.size} plano(s)? Esta ação não pode ser desfeita.`
                        : 'Tem certeza que deseja excluir este plano? Esta ação não pode ser desfeita.'
                }
                confirmText="Excluir"
                cancelText="Cancelar"
                variant="danger"
            />
        </div>
    );
}
