'use client';

import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import {
    ArrowLeftIcon,
    CheckCircleIcon,
    UserGroupIcon,
    ChartBarIcon,
    FolderIcon,
    LifebuoyIcon,
    CreditCardIcon,
    DocumentTextIcon,
    ArchiveBoxIcon,
    ShareIcon
} from '@heroicons/react/24/outline';

// Mapeamento de ícones para cada solução
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 Plan {
    id: string;
    name: string;
    slug: string;
    description: string;
    min_users: number;
    max_users: number;
    monthly_price: number | null;
    annual_price: number | null;
    features: string[];
    differentiators: string[];
    storage_gb: number;
    is_active: boolean;
    created_at: string;
}

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

export default function EditPlanPage() {
    const router = useRouter();
    const params = useParams();
    const planId = params.id as string;

    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState(false);
    const [plan, setPlan] = useState<Plan | null>(null);
    const [formData, setFormData] = useState<Partial<Plan>>({});

    const [allSolutions, setAllSolutions] = useState<Solution[]>([]);
    const [selectedSolutions, setSelectedSolutions] = useState<string[]>([]);
    const [loadingSolutions, setLoadingSolutions] = useState(true);

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (!token) {
            router.push('/login');
            return;
        }

        fetchPlan();
        fetchSolutions();
        fetchPlanSolutions();
    }, [planId, router]);

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

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

            const data = await response.json();
            setPlan(data.plan);
            setFormData(data.plan);
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Erro ao carregar plano');
        } finally {
            setLoading(false);
        }
    };

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

            if (response.ok) {
                const data = await response.json();
                setAllSolutions(data.solutions || []);
            }
        } catch (err) {
            console.error('Erro ao carregar soluções:', err);
        }
    };

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

            if (response.ok) {
                const data = await response.json();
                const solutionIds = data.solutions?.map((s: Solution) => s.id) || [];
                setSelectedSolutions(solutionIds);
            }
        } catch (err) {
            console.error('Erro ao carregar soluções do plano:', err);
        } finally {
            setLoadingSolutions(false);
        }
    };

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

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

    const handleSave = async () => {
        try {
            setSaving(true);
            setError(null);
            setSuccess(false);

            const token = localStorage.getItem('token');

            // Parse features e differentiators
            const features = (formData.features as any)
                .split(',')
                .map((f: string) => f.trim())
                .filter((f: string) => f.length > 0);

            const differentiators = (formData.differentiators as any)
                .split(',')
                .map((d: string) => d.trim())
                .filter((d: string) => d.length > 0);

            const payload = {
                ...formData,
                features,
                differentiators,
            };

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

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.message || 'Erro ao atualizar plano');
            }

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

            if (!solutionsResponse.ok) {
                throw new Error('Erro ao atualizar soluções do plano');
            }

            setSuccess(true);
            setTimeout(() => setSuccess(false), 3000);
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Erro ao atualizar plano');
        } finally {
            setSaving(false);
        }
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
            </div>
        );
    }

    if (!plan) {
        return (
            <div className="text-center py-12">
                <p className="text-red-600 dark:text-red-400">Plano não encontrado</p>
            </div>
        );
    }

    return (
        <div className="p-6 max-w-[1600px] mx-auto space-y-6">
            {/* Header */}
            <div className="flex items-center gap-4 mb-6">
                <button
                    onClick={() => router.back()}
                    className="inline-flex items-center gap-2 text-zinc-500 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-200 transition-colors"
                >
                    <ArrowLeftIcon className="w-4 h-4" />
                    Voltar
                </button>
            </div>

            <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">Editar Plano</h1>
                    <p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">{plan.name}</p>
                </div>
            </div>

            {/* Success Message */}
            {success && (
                <div className="rounded-xl bg-emerald-50 dark:bg-emerald-900/20 p-4 border border-emerald-200 dark:border-emerald-800 flex items-center gap-3">
                    <CheckCircleIcon className="h-5 w-5 text-emerald-600 dark:text-emerald-400 flex-shrink-0" />
                    <p className="text-sm font-medium text-emerald-800 dark:text-emerald-400">Plano atualizado com sucesso!</p>
                </div>
            )}

            {/* Error Message */}
            {error && (
                <div className="rounded-xl 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>
            )}

            {/* Form Card */}
            <div className="bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden">
                <form className="p-6" onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
                    <div className="space-y-6">
                        {/* Row 1: Nome e Slug */}
                        <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}
                                    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}
                                    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>

                        {/* Descrição */}
                        <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>

                        {/* Row 2: Usuários */}
                        <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>
                                <input
                                    type="number"
                                    name="min_users"
                                    value={formData.min_users || 1}
                                    onChange={handleInputChange}
                                    min="1"
                                    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">
                                    Máximo de Usuários (-1 = ilimitado)
                                </label>
                                <input
                                    type="number"
                                    name="max_users"
                                    value={formData.max_users || 30}
                                    onChange={handleInputChange}
                                    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>

                        {/* Row 3: Preços */}
                        <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 (BRL)
                                </label>
                                <input
                                    type="number"
                                    name="monthly_price"
                                    value={formData.monthly_price || ''}
                                    onChange={handleInputChange}
                                    step="0.01"
                                    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">
                                    Preço Anual (BRL)
                                </label>
                                <input
                                    type="number"
                                    name="annual_price"
                                    value={formData.annual_price || ''}
                                    onChange={handleInputChange}
                                    step="0.01"
                                    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>

                        {/* Armazenamento */}
                        <div>
                            <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                                Armazenamento (GB)
                            </label>
                            <input
                                type="number"
                                name="storage_gb"
                                value={formData.storage_gb || 1}
                                onChange={handleInputChange}
                                min="1"
                                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>

                        {/* Features */}
                        <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={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>

                        {/* Differentiators */}
                        <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={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>

                        {/* Soluções Incluídas */}
                        <div className="pt-6 border-t border-zinc-200 dark:border-zinc-700">
                            <div className="mb-4">
                                <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">
                                    Selecione quais soluções estarão disponíveis para agências com este plano
                                </p>
                            </div>

                            {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-4">
                                    {allSolutions.map((solution) => (
                                        <label
                                            key={solution.id}
                                            className={`flex items-start gap-3 p-4 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-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)'
                                                }}
                                            />
                                            <div className="flex-1">
                                                <div className="flex items-center gap-3">
                                                    <div className="w-8 h-8 rounded-lg bg-white dark:bg-zinc-800 border-2 flex items-center justify-center flex-shrink-0" style={{ borderColor: 'var(--brand-color)' }}>
                                                        {(() => {
                                                            const Icon = SOLUTION_ICONS[solution.slug] || FolderIcon;
                                                            return <Icon className="w-4 h-4 text-[var(--brand-color)]" />;
                                                        })()}
                                                    </div>
                                                    <span className="font-medium text-zinc-900 dark:text-white">
                                                        {solution.name}
                                                    </span>
                                                    {!solution.is_active && (
                                                        <span className="px-2 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-sm text-zinc-600 dark:text-zinc-400">
                                                        {solution.description}
                                                    </p>
                                                )}
                                                <code className="mt-1 inline-block text-xs text-zinc-500 dark:text-zinc-500">
                                                    {solution.slug}
                                                </code>
                                            </div>
                                        </label>
                                    ))}
                                </div>
                            )}

                            {selectedSolutions.length > 0 && (
                                <div className="mt-4 p-4 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>

                        {/* Status Checkbox */}
                        <div className="pt-4 border-t border-zinc-200 dark:border-zinc-700">
                            <label className="flex items-center gap-3">
                                <input
                                    type="checkbox"
                                    name="is_active"
                                    checked={formData.is_active || false}
                                    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>

                        {/* Buttons */}
                        <div className="flex gap-3 pt-6 border-t border-zinc-200 dark:border-zinc-700">
                            <button
                                type="submit"
                                disabled={saving}
                                className="flex-1 px-6 py-2.5 bg-gradient-to-r 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>
                            <button
                                type="button"
                                onClick={() => router.back()}
                                disabled={saving}
                                className="flex-1 px-6 py-2.5 border border-zinc-300 dark:border-zinc-600 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>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    );
}
