"use client";

import { Fragment, useEffect, useState } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import Tabs, { TabItem } from '@/components/ui/Tabs';
import { useToast } from '@/components/layout/ToastContext';
import {
    XMarkIcon,
    SparklesIcon,
    UserGroupIcon,
    ChartBarIcon,
    FolderIcon,
    LifebuoyIcon,
    CreditCardIcon,
    DocumentTextIcon,
    ArchiveBoxIcon,
    ShareIcon,
    DocumentIcon,
    CurrencyDollarIcon,
    SparklesIcon as SparklesIconOutline,
    CubeIcon,
    PlusIcon,
    MinusIcon
} from '@heroicons/react/24/outline';

const SOLUTION_ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
    'crm': UserGroupIcon,
    'erp': ChartBarIcon,
    'projetos': FolderIcon,
    'helpdesk': LifebuoyIcon,
    'pagamentos': CreditCardIcon,
    'contratos': DocumentTextIcon,
    'documentos': ArchiveBoxIcon,
    'social': ShareIcon,
};

interface Solution {
    id: string;
    name: string;
    slug: string;
    description?: string;
    is_active: boolean;
}

interface EditPlanModalProps {
    isOpen: boolean;
    onClose: () => void;
    planId: string | null;
    onSuccess: () => void;
}

export default function EditPlanModal({ isOpen, onClose, planId, onSuccess }: EditPlanModalProps) {
    const toast = useToast();
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [loadingSolutions, setLoadingSolutions] = useState(true);
    const [allSolutions, setAllSolutions] = useState<Solution[]>([]);
    const [selectedSolutions, setSelectedSolutions] = useState<string[]>([]);

    const [formData, setFormData] = useState({
        name: '',
        slug: '',
        description: '',
        monthly_price: '',
        annual_price: '',
        min_users: 1,
        max_users: 30,
        storage_gb: 1,
        discount_months: 2,
        features: '' as string | string[],
        differentiators: '' as string | string[],
        is_active: true,
    });

    useEffect(() => {
        if (isOpen && planId) {
            fetchPlanData();
            fetchAllSolutions();
            fetchPlanSolutions();
        }
    }, [isOpen, planId]);

    const fetchPlanData = async () => {
        if (!planId) return;

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

            if (response.ok) {
                const data = await response.json();
                const plan = data.plan;

                console.log('Plano carregado:', plan);
                console.log('Solu\u00e7\u00f5es do plano:', plan.solutions);

                setFormData({
                    name: plan.name || '',
                    slug: plan.slug || '',
                    description: plan.description || '',
                    monthly_price: plan.monthly_price || '',
                    annual_price: plan.annual_price || '',
                    min_users: plan.min_users || 1,
                    max_users: plan.max_users || 30,
                    storage_gb: plan.storage_gb || 1,
                    discount_months: plan.discount_months || 2,
                    features: Array.isArray(plan.features) ? plan.features.join(', ') : (plan.features || ''),
                    differentiators: Array.isArray(plan.differentiators) ? plan.differentiators.join(', ') : (plan.differentiators || ''),
                    is_active: plan.is_active ?? true,
                });

                const solutionIds = plan.solutions?.map((s: Solution) => s.id) || [];
                console.log('IDs das solu\u00e7\u00f5es extra\u00eddos:', solutionIds);
                // Não seta aqui, vamos buscar via API separada
                // setSelectedSolutions(solutionIds);
            }
        } catch (error) {
            console.error('Error fetching plan:', error);
        } finally {
            setLoading(false);
        }
    };

    const fetchPlanSolutions = async () => {
        if (!planId) return;

        try {
            console.log('Buscando soluções do plano...');
            const response = await fetch(`/api/admin/plans/${planId}/solutions`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                },
            });

            if (response.ok) {
                const data = await response.json();
                console.log('Soluções do plano (via API separada):', data);
                const solutionIds = data.solutions?.map((s: Solution) => s.id) || [];
                console.log('IDs extraídos:', solutionIds);
                setSelectedSolutions(solutionIds);
            } else {
                console.error('Erro ao buscar soluções:', response.status);
            }
        } catch (error) {
            console.error('Error fetching plan solutions:', error);
        }
    };

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

            if (response.ok) {
                const data = await response.json();
                console.log('Todas as solu\u00e7\u00f5es dispon\u00edveis:', data.solutions);
                setAllSolutions(data.solutions || []);
            }
        } catch (error) {
            console.error('Error fetching solutions:', error);
        } finally {
            setLoadingSolutions(false);
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!planId) return;

        setSaving(true);

        try {
            const planPayload = {
                name: formData.name,
                slug: formData.slug,
                description: formData.description,
                monthly_price: parseFloat(String(formData.monthly_price)) || 0,
                annual_price: parseFloat(String(formData.annual_price)) || 0,
                min_users: parseInt(String(formData.min_users)) || 1,
                max_users: parseInt(String(formData.max_users)) || 30,
                storage_gb: parseInt(String(formData.storage_gb)) || 1,
                is_active: formData.is_active,
                features: typeof formData.features === 'string'
                    ? formData.features.split(',').map(f => f.trim()).filter(f => f)
                    : formData.features,
                differentiators: typeof formData.differentiators === 'string'
                    ? formData.differentiators.split(',').map(d => d.trim()).filter(d => d)
                    : formData.differentiators,
            };

            console.log('Atualizando plano:', planPayload);

            // Atualizar dados do plano
            const response = await fetch(`/api/admin/plans/${planId}`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(planPayload),
            });

            if (!response.ok) {
                const errorData = await response.json();
                console.error('Erro ao atualizar plano:', errorData);
                toast.error('Erro ao atualizar plano', errorData.message || 'Verifique os dados');
                setSaving(false);
                return;
            }

            console.log('Plano atualizado, atualizando soluções:', selectedSolutions);

            // Atualizar soluções associadas
            const solutionsResponse = await fetch(`/api/admin/plans/${planId}/solutions`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ solution_ids: selectedSolutions }),
            });

            if (!solutionsResponse.ok) {
                const errorData = await solutionsResponse.json();
                console.error('Erro ao atualizar soluções:', errorData);
                toast.error('Erro ao atualizar soluções', errorData.message || 'Verifique os dados');
                setSaving(false);
                return;
            }

            console.log('Soluções atualizadas com sucesso');
            toast.success('Plano atualizado!', 'Todas as alterações foram salvas com sucesso');
            onSuccess();
            onClose();
        } catch (error) {
            console.error('Error updating plan:', error);
            toast.error('Erro ao atualizar plano', 'Ocorreu um erro inesperado');
        } finally {
            setSaving(false);
        }
    };

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value, type } = e.target;

        if (type === 'checkbox') {
            const checked = (e.target as HTMLInputElement).checked;
            setFormData(prev => ({ ...prev, [name]: checked }));
        } else if (type === 'number') {
            const numValue = parseFloat(value) || 0;
            setFormData(prev => {
                const newData = {
                    ...prev,
                    [name]: numValue,
                };

                // Calcular preço anual automaticamente quando mensal ou discount_months muda
                if ((name === 'monthly_price' || name === 'discount_months')) {
                    const monthlyPrice = name === 'monthly_price' ? numValue : parseFloat(String(prev.monthly_price)) || 0;
                    const discountMonths = name === 'discount_months' ? numValue : prev.discount_months;

                    if (monthlyPrice > 0 && discountMonths >= 0) {
                        // Calcula: (12 meses - meses de desconto) * preço mensal
                        const monthsToPay = Math.max(0, 12 - discountMonths);
                        const annualWithDiscount = (monthlyPrice * monthsToPay).toFixed(2);
                        newData.annual_price = annualWithDiscount;
                    }
                }

                return newData;
            });
        } else {
            setFormData(prev => ({ ...prev, [name]: value }));
        }
    };

    const incrementValue = (field: 'min_users' | 'max_users' | 'storage_gb' | 'discount_months', step: number = 1) => {
        setFormData(prev => {
            const newValue = prev[field] + step;
            const newData = {
                ...prev,
                [field]: newValue,
            };

            // Recalcular preço anual se mudou discount_months
            if (field === 'discount_months') {
                const monthlyPrice = parseFloat(String(prev.monthly_price)) || 0;
                if (monthlyPrice > 0 && newValue >= 0) {
                    const monthsToPay = Math.max(0, 12 - newValue);
                    newData.annual_price = (monthlyPrice * monthsToPay).toFixed(2);
                }
            }

            return newData;
        });
    };

    const decrementValue = (field: 'min_users' | 'max_users' | 'storage_gb' | 'discount_months', step: number = 1, min: number = 0) => {
        setFormData(prev => {
            const newValue = Math.max(min, prev[field] - step);
            const newData = {
                ...prev,
                [field]: newValue,
            };

            // Recalcular preço anual se mudou discount_months
            if (field === 'discount_months') {
                const monthlyPrice = parseFloat(String(prev.monthly_price)) || 0;
                if (monthlyPrice > 0 && newValue >= 0) {
                    const monthsToPay = Math.max(0, 12 - newValue);
                    newData.annual_price = (monthlyPrice * monthsToPay).toFixed(2);
                }
            }

            return newData;
        });
    };

    const handleClose = () => {
        if (!saving) {
            onClose();
        }
    };

    // Configuração dos tabs
    const tabsConfig: TabItem[] = [
        {
            name: 'Dados Básicos',
            icon: DocumentIcon,
            content: (
                <div className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                Nome do Plano *
                            </label>
                            <input
                                type="text"
                                name="name"
                                value={formData.name}
                                onChange={handleInputChange}
                                required
                                className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                Slug *
                            </label>
                            <input
                                type="text"
                                name="slug"
                                value={formData.slug}
                                onChange={handleInputChange}
                                required
                                className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                            />
                        </div>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                            Descrição
                        </label>
                        <textarea
                            name="description"
                            value={formData.description}
                            onChange={handleInputChange}
                            rows={3}
                            className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all resize-none"
                        />
                    </div>

                    <div className="pt-2">
                        <label className="flex items-center gap-3">
                            <input
                                type="checkbox"
                                name="is_active"
                                checked={formData.is_active}
                                onChange={handleInputChange}
                                className="h-5 w-5 rounded border-zinc-300 dark:border-zinc-600 text-[var(--brand-color)] focus:ring-[var(--brand-color)] dark:bg-zinc-800 cursor-pointer"
                                style={{ accentColor: 'var(--brand-color)' }}
                            />
                            <span className="text-sm font-medium text-zinc-900 dark:text-white">Plano Ativo</span>
                        </label>
                    </div>
                </div>
            )
        },
        {
            name: 'Limites e Preços',
            icon: CurrencyDollarIcon,
            content: (
                <div className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                Mínimo de Usuários
                            </label>
                            <div className="flex items-center gap-2">
                                <button
                                    type="button"
                                    onClick={() => decrementValue('min_users', 1, 1)}
                                    className="p-2 rounded-lg border border-zinc-200 dark:border-zinc-700 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    <MinusIcon className="w-4 h-4 text-zinc-600 dark:text-zinc-400" />
                                </button>
                                <input
                                    type="number"
                                    name="min_users"
                                    value={formData.min_users}
                                    onChange={handleInputChange}
                                    min="1"
                                    className="flex-1 px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white text-center font-medium focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                />
                                <button
                                    type="button"
                                    onClick={() => incrementValue('min_users', 1)}
                                    className="p-2 rounded-lg border border-zinc-200 dark:border-zinc-700 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    <PlusIcon className="w-4 h-4 text-zinc-600 dark:text-zinc-400" />
                                </button>
                            </div>
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                Máximo de Usuários
                            </label>
                            <div className="flex items-center gap-2">
                                <button
                                    type="button"
                                    onClick={() => decrementValue('max_users', 5, -1)}
                                    className="p-2 rounded-lg border border-zinc-200 dark:border-zinc-700 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    <MinusIcon className="w-4 h-4 text-zinc-600 dark:text-zinc-400" />
                                </button>
                                <input
                                    type="number"
                                    name="max_users"
                                    value={formData.max_users}
                                    onChange={handleInputChange}
                                    className="flex-1 px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white text-center font-medium focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                />
                                <button
                                    type="button"
                                    onClick={() => incrementValue('max_users', 5)}
                                    className="p-2 rounded-lg border border-zinc-200 dark:border-zinc-700 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    <PlusIcon className="w-4 h-4 text-zinc-600 dark:text-zinc-400" />
                                </button>
                            </div>
                            <p className="mt-2 text-xs text-zinc-500 dark:text-zinc-400">
                                Use -1 para ilimitado
                            </p>
                        </div>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                            Armazenamento (GB)
                        </label>
                        <div className="flex items-center gap-2">
                            <button
                                type="button"
                                onClick={() => decrementValue('storage_gb', 1, 1)}
                                className="p-2 rounded-lg border border-zinc-200 dark:border-zinc-700 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                            >
                                <MinusIcon className="w-4 h-4 text-zinc-600 dark:text-zinc-400" />
                            </button>
                            <input
                                type="number"
                                name="storage_gb"
                                value={formData.storage_gb}
                                onChange={handleInputChange}
                                min="1"
                                className="flex-1 px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white text-center font-medium focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                            />
                            <button
                                type="button"
                                onClick={() => incrementValue('storage_gb', 1)}
                                className="p-2 rounded-lg border border-zinc-200 dark:border-zinc-700 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                            >
                                <PlusIcon className="w-4 h-4 text-zinc-600 dark:text-zinc-400" />
                            </button>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                Preço Mensal (R$) *
                            </label>
                            <div className="relative">
                                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500">R$</span>
                                <input
                                    type="number"
                                    name="monthly_price"
                                    value={formData.monthly_price}
                                    onChange={handleInputChange}
                                    placeholder="199.99"
                                    step="0.01"
                                    className="w-full pl-10 pr-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                />
                            </div>
                            <p className="mt-2 text-xs text-zinc-500 dark:text-zinc-400">
                                Digite o preço mensal
                            </p>
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                Meses Grátis (Desconto)
                            </label>
                            <div className="flex items-center gap-2">
                                <button
                                    type="button"
                                    onClick={() => decrementValue('discount_months', 1, 0)}
                                    className="p-2 rounded-lg border border-zinc-200 dark:border-zinc-700 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    <MinusIcon className="w-4 h-4 text-zinc-600 dark:text-zinc-400" />
                                </button>
                                <input
                                    type="number"
                                    name="discount_months"
                                    value={formData.discount_months}
                                    onChange={handleInputChange}
                                    min="0"
                                    max="11"
                                    className="flex-1 px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white text-center font-medium focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                                />
                                <button
                                    type="button"
                                    onClick={() => incrementValue('discount_months', 1)}
                                    className="p-2 rounded-lg border border-zinc-200 dark:border-zinc-700 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    <PlusIcon className="w-4 h-4 text-zinc-600 dark:text-zinc-400" />
                                </button>
                            </div>
                            <p className="mt-2 text-xs text-zinc-500 dark:text-zinc-400">
                                Ex: 2 = cliente paga 10 meses
                            </p>
                        </div>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                            Preço Anual (R$) <span className="text-emerald-600 dark:text-emerald-400">✓ Auto</span>
                        </label>
                        <div className="relative">
                            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500">R$</span>
                            <input
                                type="number"
                                name="annual_price"
                                value={formData.annual_price}
                                onChange={handleInputChange}
                                placeholder="Calculado automaticamente"
                                step="0.01"
                                className="w-full pl-10 pr-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                            />
                        </div>
                        <p className="mt-2 text-xs text-emerald-600 dark:text-emerald-400">
                            ✓ Calculado automaticamente com base no preço mensal e desconto
                        </p>
                    </div>
                </div>
            )
        },
        {
            name: 'Recursos',
            icon: SparklesIconOutline,
            content: (
                <div className="space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                            Recursos <span className="text-xs font-normal text-zinc-500 dark:text-zinc-400">(separados por vírgula)</span>
                        </label>
                        <textarea
                            name="features"
                            value={typeof formData.features === 'string' ? formData.features : formData.features.join(', ')}
                            onChange={handleInputChange}
                            rows={4}
                            placeholder="Ex: Gestão de leads, Relatórios avançados, API ilimitada"
                            className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all resize-none"
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                            Diferenciais <span className="text-xs font-normal text-zinc-500 dark:text-zinc-400">(separados por vírgula)</span>
                        </label>
                        <textarea
                            name="differentiators"
                            value={typeof formData.differentiators === 'string' ? formData.differentiators : formData.differentiators.join(', ')}
                            onChange={handleInputChange}
                            rows={4}
                            placeholder="Ex: Suporte prioritário, Treinamento personalizado, Consultoria mensal"
                            className="w-full px-3 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all resize-none"
                        />
                    </div>
                </div>
            )
        },
        {
            name: 'Soluções',
            icon: CubeIcon,
            content: (
                <div className="space-y-4">
                    <div>
                        <h3 className="text-base font-medium text-zinc-900 dark:text-white mb-1">
                            Soluções Incluídas
                        </h3>
                        <p className="text-sm text-zinc-600 dark:text-zinc-400 mb-4">
                            Selecione quais soluções estarão disponíveis para agências com este plano
                        </p>

                        {loadingSolutions ? (
                            <div className="flex items-center justify-center py-8">
                                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
                            </div>
                        ) : allSolutions.length === 0 ? (
                            <div className="rounded-lg bg-zinc-50 dark:bg-zinc-800 p-6 text-center">
                                <p className="text-sm text-zinc-600 dark:text-zinc-400">
                                    Nenhuma solução cadastrada ainda.
                                </p>
                            </div>
                        ) : (
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                {allSolutions.map((solution) => (
                                    <label
                                        key={solution.id}
                                        className={`flex items-start gap-3 p-3 rounded-lg border-2 cursor-pointer transition-all ${selectedSolutions.includes(solution.id)
                                            ? 'bg-zinc-50 dark:bg-zinc-800/50'
                                            : 'border-zinc-200 dark:border-zinc-700 hover:border-zinc-300 dark:hover:border-zinc-600'
                                            }`}
                                        style={{
                                            borderColor: selectedSolutions.includes(solution.id) ? 'var(--brand-color)' : undefined
                                        }}
                                    >
                                        <input
                                            type="checkbox"
                                            checked={selectedSolutions.includes(solution.id)}
                                            onChange={(e) => {
                                                if (e.target.checked) {
                                                    setSelectedSolutions([...selectedSolutions, solution.id]);
                                                } else {
                                                    setSelectedSolutions(selectedSolutions.filter(id => id !== solution.id));
                                                }
                                            }}
                                            className="mt-0.5 h-4 w-4 rounded border-zinc-300 dark:border-zinc-600 text-[var(--brand-color)] focus:ring-[var(--brand-color)] dark:bg-zinc-800 cursor-pointer"
                                            style={{ accentColor: 'var(--brand-color)' }}
                                        />
                                        <div className="flex-1 min-w-0">
                                            <div className="flex items-center gap-2">
                                                <div className="w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0" style={{ background: 'var(--gradient)' }}>
                                                    {(() => {
                                                        const Icon = SOLUTION_ICONS[solution.slug] || FolderIcon;
                                                        return <Icon className="w-3.5 h-3.5 text-white" />;
                                                    })()}
                                                </div>
                                                <span className="text-sm font-medium text-zinc-900 dark:text-white truncate">
                                                    {solution.name}
                                                </span>
                                                {!solution.is_active && (
                                                    <span className="px-1.5 py-0.5 text-xs font-medium bg-zinc-200 dark:bg-zinc-700 text-zinc-600 dark:text-zinc-400 rounded">
                                                        Inativo
                                                    </span>
                                                )}
                                            </div>
                                            {solution.description && (
                                                <p className="mt-1 text-xs text-zinc-600 dark:text-zinc-400 line-clamp-1">
                                                    {solution.description}
                                                </p>
                                            )}
                                        </div>
                                    </label>
                                ))}
                            </div>
                        )}

                        {selectedSolutions.length > 0 && (
                            <div className="mt-4 p-3 rounded-lg border" style={{
                                backgroundColor: 'var(--brand-color-light, rgba(59, 130, 246, 0.1))',
                                borderColor: 'var(--brand-color)'
                            }}>
                                <p className="text-sm font-medium" style={{ color: 'var(--brand-color)' }}>
                                    {selectedSolutions.length} {selectedSolutions.length === 1 ? 'solução selecionada' : 'soluções selecionadas'}
                                </p>
                            </div>
                        )}
                    </div>
                </div>
            )
        }
    ];

    return (
        <Transition appear show={isOpen} as={Fragment}>
            <Dialog as="div" className="relative z-50" onClose={handleClose}>
                <Transition.Child
                    as={Fragment}
                    enter="ease-out duration-300"
                    enterFrom="opacity-0"
                    enterTo="opacity-100"
                    leave="ease-in duration-200"
                    leaveFrom="opacity-100"
                    leaveTo="opacity-0"
                >
                    <div className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm" />
                </Transition.Child>

                <div className="fixed inset-0 overflow-y-auto">
                    <div className="flex min-h-full items-center justify-center p-4">
                        <Transition.Child
                            as={Fragment}
                            enter="ease-out duration-300"
                            enterFrom="opacity-0 scale-95"
                            enterTo="opacity-100 scale-100"
                            leave="ease-in duration-200"
                            leaveFrom="opacity-100 scale-100"
                            leaveTo="opacity-0 scale-95"
                        >
                            <Dialog.Panel className="w-full max-w-4xl transform overflow-hidden rounded-2xl bg-white dark:bg-zinc-900 text-left align-middle shadow-xl transition-all border border-zinc-200 dark:border-zinc-800">
                                {loading ? (
                                    <div className="flex items-center justify-center p-12">
                                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
                                    </div>
                                ) : (
                                    <>
                                        {/* Header */}
                                        <div className="flex items-start justify-between p-6 border-b border-zinc-200 dark:border-zinc-700">
                                            <div className="flex items-start gap-4">
                                                <div
                                                    className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl shadow-lg"
                                                    style={{ background: 'var(--gradient)' }}
                                                >
                                                    <SparklesIcon className="h-6 w-6 text-white" />
                                                </div>
                                                <div>
                                                    <Dialog.Title className="text-xl font-bold text-zinc-900 dark:text-white">
                                                        Editar Plano
                                                    </Dialog.Title>
                                                    <p className="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
                                                        Atualize as informações e soluções do plano
                                                    </p>
                                                </div>
                                            </div>
                                            <button
                                                type="button"
                                                className="rounded-lg p-1.5 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                                                onClick={handleClose}
                                                disabled={saving}
                                            >
                                                <XMarkIcon className="h-5 w-5" />
                                            </button>
                                        </div>

                                        {/* Form com Tabs */}
                                        <form onSubmit={handleSubmit} className="p-6">
                                            <Tabs tabs={tabsConfig} />

                                            {/* Footer com botões */}
                                            <div className="mt-6 pt-6 border-t border-zinc-200 dark:border-zinc-700 flex gap-3">
                                                <button
                                                    type="button"
                                                    onClick={handleClose}
                                                    disabled={saving}
                                                    className="flex-1 px-4 py-2.5 border border-zinc-200 dark:border-zinc-700 text-zinc-700 dark:text-zinc-300 font-medium rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                                                >
                                                    Cancelar
                                                </button>
                                                <button
                                                    type="submit"
                                                    disabled={saving}
                                                    className="flex-1 px-4 py-2.5 text-white font-medium rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-sm hover:shadow-md"
                                                    style={{ backgroundImage: 'var(--gradient)' }}
                                                >
                                                    {saving ? 'Salvando...' : 'Salvar Alterações'}
                                                </button>
                                            </div>
                                        </form>
                                    </>
                                )}
                            </Dialog.Panel>
                        </Transition.Child>
                    </div>
                </div>
            </Dialog>
        </Transition>
    );
}
