'use client';

import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { ArrowLeftIcon, CheckCircleIcon } from '@heroicons/react/24/outline';

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;
}

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>>({});

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

        fetchPlan();
    }, [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 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');
            }

            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="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 plano...</p>
                </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="space-y-6">
            {/* Header */}
            <div className="flex items-center gap-4">
                <button
                    onClick={() => router.back()}
                    className="p-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-lg transition-colors"
                >
                    <ArrowLeftIcon className="h-6 w-6 text-zinc-600 dark:text-zinc-400" />
                </button>
                <div>
                    <h1 className="text-3xl font-bold text-zinc-900 dark:text-white">Editar Plano</h1>
                    <p className="mt-1 text-sm text-zinc-600 dark:text-zinc-400">{plan.name}</p>
                </div>
            </div>

            {/* Success Message */}
            {success && (
                <div className="rounded-lg 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-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>
            )}

            {/* Form Card */}
            <div className="rounded-2xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 p-6 sm:p-8">
                <form className="space-y-6" onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
                    {/* Row 1: Nome e Slug */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
                                Nome do Plano
                            </label>
                            <input
                                type="text"
                                name="name"
                                value={formData.name || ''}
                                onChange={handleInputChange}
                                className="w-full px-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
                                Slug
                            </label>
                            <input
                                type="text"
                                name="slug"
                                value={formData.slug || ''}
                                onChange={handleInputChange}
                                className="w-full px-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                            />
                        </div>
                    </div>

                    {/* Descrição */}
                    <div>
                        <label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
                            Descrição
                        </label>
                        <textarea
                            name="description"
                            value={formData.description || ''}
                            onChange={handleInputChange}
                            rows={3}
                            className="w-full px-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all resize-none"
                        />
                    </div>

                    {/* Row 2: Usuários */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label className="block text-sm font-semibold text-zinc-900 dark:text-white 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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-semibold text-zinc-900 dark:text-white 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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                            />
                        </div>
                    </div>

                    {/* Row 3: Preços */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label className="block text-sm font-semibold text-zinc-900 dark:text-white 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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-semibold text-zinc-900 dark:text-white 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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                            />
                        </div>
                    </div>

                    {/* Armazenamento */}
                    <div>
                        <label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
                            Armazenamento (GB)
                        </label>
                        <input
                            type="number"
                            name="storage_gb"
                            value={formData.storage_gb || 1}
                            onChange={handleInputChange}
                            min="1"
                            className="w-full px-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                        />
                    </div>

                    {/* Features */}
                    <div>
                        <label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
                            Recursos <span className="text-xs font-normal text-zinc-500">(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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all resize-none"
                        />
                    </div>

                    {/* Differentiators */}
                    <div>
                        <label className="block text-sm font-semibold text-zinc-900 dark:text-white mb-2">
                            Diferenciais <span className="text-xs font-normal text-zinc-500">(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-4 py-2.5 border border-zinc-300 dark:border-zinc-600 rounded-lg bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all resize-none"
                        />
                    </div>

                    {/* Status Checkbox */}
                    <div className="pt-4 border-t border-zinc-200 dark:border-zinc-800">
                        <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-blue-600 focus:ring-blue-500 dark:bg-zinc-800 cursor-pointer"
                            />
                            <span className="text-sm font-semibold 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-800">
                        <button
                            type="submit"
                            disabled={saving}
                            className="flex-1 px-6 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 disabled:cursor-not-allowed text-white font-semibold rounded-lg transition-colors"
                        >
                            {saving ? 'Salvando...' : 'Salvar Alterações'}
                        </button>
                        <button
                            type="button"
                            onClick={() => router.back()}
                            disabled={saving}
                            className="flex-1 px-6 py-3 border border-zinc-300 dark:border-zinc-600 text-zinc-700 dark:text-zinc-300 font-semibold rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        >
                            Cancelar
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}
