'use client';

import { useEffect, useState } from 'react';
import { PencilIcon, TrashIcon, PlusIcon } from '@heroicons/react/24/outline';
import CreatePlanModal from '@/components/plans/CreatePlanModal';

export default function PlansPage() {
    const [plans, setPlans] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [isModalOpen, setIsModalOpen] = useState(false);

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

    const fetchPlans = async () => {
        try {
            setLoading(true);
            const token = localStorage.getItem('token');
            const response = await fetch('/api/admin/plans', {
                headers: {
                    'Authorization': `Bearer ${token}`,
                },
            });

            if (!response.ok) {
                throw new Error('Erro ao carregar planos');
            }

            const data = await response.json();
            setPlans(data.plans || []);
            setError('');
        } catch (err: any) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleDeletePlan = async (id: string) => {
        if (!confirm('Tem certeza que deseja deletar este plano? Esta ação não pode ser desfeita.')) {
            return;
        }

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

            if (!response.ok) {
                throw new Error('Erro ao deletar plano');
            }

            fetchPlans();
        } catch (err: any) {
            setError(err.message);
        }
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="text-center">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
                    <p className="text-zinc-600 dark:text-zinc-400">Carregando planos...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex justify-between items-center">
                <div>
                    <h1 className="text-3xl font-bold text-zinc-900 dark:text-white">Planos</h1>
                    <p className="mt-2 text-sm text-zinc-600 dark:text-zinc-400">
                        Gerencie os planos de assinatura disponíveis para as agências
                    </p>
                </div>
                <button
                    onClick={() => setIsModalOpen(true)}
                    className="inline-flex items-center gap-2 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition-colors shadow-sm"
                >
                    <PlusIcon className="h-5 w-5" />
                    Novo Plano
                </button>
            </div>

            {/* Error Message */}
            {error && (
                <div className="rounded-lg bg-red-50 dark:bg-red-900/20 p-4 border border-red-200 dark:border-red-800">
                    <p className="text-sm font-medium text-red-800 dark:text-red-400">{error}</p>
                </div>
            )}

            {/* Plans Grid */}
            {plans.length > 0 ? (
                <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
                    {plans.map((plan) => (
                        <div
                            key={plan.id}
                            className="group rounded-2xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 hover:shadow-lg dark:hover:shadow-2xl transition-all duration-200 overflow-hidden"
                        >
                            {/* Header */}
                            <div className="px-6 pt-6 pb-4 border-b border-zinc-100 dark:border-zinc-800">
                                <div className="flex items-start justify-between mb-2">
                                    <div>
                                        <h3 className="text-lg font-semibold text-zinc-900 dark:text-white">
                                            {plan.name}
                                        </h3>
                                        {!plan.is_active && (
                                            <span className="inline-block mt-2 px-2 py-1 rounded-full text-xs font-semibold bg-zinc-100 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400">
                                                Inativo
                                            </span>
                                        )}
                                    </div>
                                    {plan.is_active && (
                                        <span className="px-2.5 py-1 rounded-full text-xs font-semibold bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-400">
                                            Ativo
                                        </span>
                                    )}
                                </div>
                                {plan.description && (
                                    <p className="text-sm text-zinc-600 dark:text-zinc-400 line-clamp-2">
                                        {plan.description}
                                    </p>
                                )}
                            </div>

                            {/* Content */}
                            <div className="px-6 py-4 space-y-4">
                                {/* Pricing */}
                                <div className="space-y-2">
                                    {plan.monthly_price && (
                                        <div className="flex justify-between items-center">
                                            <span className="text-sm text-zinc-600 dark:text-zinc-400">Mensal</span>
                                            <span className="text-2xl font-bold text-zinc-900 dark:text-white">
                                                R$ <span className="text-xl">{parseFloat(plan.monthly_price).toFixed(2)}</span>
                                            </span>
                                        </div>
                                    )}
                                    {plan.annual_price && (
                                        <div className="flex justify-between items-center">
                                            <span className="text-sm text-zinc-600 dark:text-zinc-400">Anual</span>
                                            <span className="text-2xl font-bold text-zinc-900 dark:text-white">
                                                R$ <span className="text-xl">{parseFloat(plan.annual_price).toFixed(2)}</span>
                                            </span>
                                        </div>
                                    )}
                                </div>

                                {/* Stats */}
                                <div className="grid grid-cols-2 gap-3 pt-2 border-t border-zinc-100 dark:border-zinc-800">
                                    <div className="p-3 bg-zinc-50 dark:bg-zinc-800 rounded-lg">
                                        <p className="text-xs text-zinc-600 dark:text-zinc-400 mb-1">Usuários</p>
                                        <p className="text-sm font-semibold text-zinc-900 dark:text-white">
                                            {plan.min_users} - {plan.max_users === -1 ? '∞' : plan.max_users}
                                        </p>
                                    </div>
                                    <div className="p-3 bg-zinc-50 dark:bg-zinc-800 rounded-lg">
                                        <p className="text-xs text-zinc-600 dark:text-zinc-400 mb-1">Armazenamento</p>
                                        <p className="text-sm font-semibold text-zinc-900 dark:text-white">
                                            {plan.storage_gb} GB
                                        </p>
                                    </div>
                                </div>

                                {/* Features */}
                                {plan.features && plan.features.length > 0 && (
                                    <div className="pt-2">
                                        <p className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 uppercase tracking-wide mb-2">
                                            Recursos
                                        </p>
                                        <ul className="space-y-1">
                                            {plan.features.slice(0, 4).map((feature: string, idx: number) => (
                                                <li key={idx} className="text-xs text-zinc-600 dark:text-zinc-400 flex items-center gap-2">
                                                    <span className="inline-block h-1.5 w-1.5 bg-blue-600 rounded-full"></span>
                                                    {feature}
                                                </li>
                                            ))}
                                            {plan.features.length > 4 && (
                                                <li className="text-xs text-zinc-600 dark:text-zinc-400 italic">
                                                    +{plan.features.length - 4} mais
                                                </li>
                                            )}
                                        </ul>
                                    </div>
                                )}

                                {/* Differentiators */}
                                {plan.differentiators && plan.differentiators.length > 0 && (
                                    <div className="pt-2">
                                        <p className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 uppercase tracking-wide mb-2">
                                            Diferenciais
                                        </p>
                                        <ul className="space-y-1">
                                            {plan.differentiators.slice(0, 2).map((diff: string, idx: number) => (
                                                <li key={idx} className="text-xs text-zinc-600 dark:text-zinc-400 flex items-center gap-2">
                                                    <span className="inline-block h-1.5 w-1.5 bg-emerald-600 rounded-full"></span>
                                                    {diff}
                                                </li>
                                            ))}
                                            {plan.differentiators.length > 2 && (
                                                <li className="text-xs text-zinc-600 dark:text-zinc-400 italic">
                                                    +{plan.differentiators.length - 2} mais
                                                </li>
                                            )}
                                        </ul>
                                    </div>
                                )}
                            </div>

                            {/* Footer */}
                            <div className="px-6 py-4 bg-zinc-50 dark:bg-zinc-800/50 border-t border-zinc-100 dark:border-zinc-800 flex gap-2">
                                <a
                                    href={`/superadmin/plans/${plan.id}`}
                                    className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 hover:bg-blue-200 dark:hover:bg-blue-900/50 font-medium rounded-lg transition-colors text-sm"
                                >
                                    <PencilIcon className="h-4 w-4" />
                                    Editar
                                </a>
                                <button
                                    onClick={() => handleDeletePlan(plan.id)}
                                    className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 hover:bg-red-200 dark:hover:bg-red-900/50 font-medium rounded-lg transition-colors text-sm"
                                >
                                    <TrashIcon className="h-4 w-4" />
                                    Deletar
                                </button>
                            </div>
                        </div>
                    ))}
                </div>
            ) : (
                <div className="text-center py-12">
                    <div className="text-zinc-400 dark:text-zinc-600 mb-2">
                        <svg
                            className="h-12 w-12 mx-auto"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={1.5}
                                d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                            />
                        </svg>
                    </div>
                    <p className="text-zinc-600 dark:text-zinc-400 text-lg font-medium">Nenhum plano criado</p>
                    <p className="text-zinc-500 dark:text-zinc-500 text-sm">Clique no botão acima para criar o primeiro plano</p>
                </div>
            )}

            {/* Create Plan Modal */}
            <CreatePlanModal
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                onSuccess={() => {
                    fetchPlans();
                }}
            />
        </div>
    );
}
