'use client';

import { Fragment, useState } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import {
    XMarkIcon,
    SparklesIcon,
} from '@heroicons/react/24/outline';

interface CreatePlanModalProps {
    isOpen: boolean;
    onClose: () => void;
    onSuccess: (plan: any) => void;
}

interface CreatePlanForm {
    name: string;
    slug: string;
    description: string;
    min_users: number;
    max_users: number;
    monthly_price: string;
    annual_price: string;
    features: string;
    differentiators: string;
    storage_gb: number;
    is_active: boolean;
}

function classNames(...classes: string[]) {
    return classes.filter(Boolean).join(' ');
}

export default function CreatePlanModal({ isOpen, onClose, onSuccess }: CreatePlanModalProps) {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [formData, setFormData] = useState<CreatePlanForm>({
        name: '',
        slug: '',
        description: '',
        min_users: 1,
        max_users: 30,
        monthly_price: '',
        annual_price: '',
        features: '',
        differentiators: '',
        storage_gb: 1,
        is_active: true,
    });

    const handleChange = (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]: parseFloat(value) || 0,
            }));
        } else {
            setFormData(prev => ({
                ...prev,
                [name]: value,
            }));
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        setError('');

        try {
            // Validações básicas
            if (!formData.name || !formData.slug) {
                setError('Nome e Slug são obrigatórios');
                setLoading(false);
                return;
            }

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

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

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

            const payload = {
                name: formData.name,
                slug: formData.slug,
                description: formData.description,
                min_users: formData.min_users,
                max_users: formData.max_users,
                monthly_price: formData.monthly_price ? parseFloat(formData.monthly_price) : null,
                annual_price: formData.annual_price ? parseFloat(formData.annual_price) : null,
                features,
                differentiators,
                storage_gb: formData.storage_gb,
                is_active: formData.is_active,
            };

            const response = await fetch('/api/admin/plans', {
                method: 'POST',
                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 criar plano');
            }

            const data = await response.json();
            onSuccess(data.plan);
            onClose();
        } catch (err: any) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleClose = () => {
        if (!loading) {
            setError('');
            setFormData({
                name: '',
                slug: '',
                description: '',
                min_users: 1,
                max_users: 30,
                monthly_price: '',
                annual_price: '',
                features: '',
                differentiators: '',
                storage_gb: 1,
                is_active: true,
            });
            onClose();
        }
    };

    return (
        <Transition.Root 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-opacity" />
                </Transition.Child>

                <div className="fixed inset-0 z-10 overflow-y-auto">
                    <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
                        <Transition.Child
                            as={Fragment}
                            enter="ease-out duration-300"
                            enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                            enterTo="opacity-100 translate-y-0 sm:scale-100"
                            leave="ease-in duration-200"
                            leaveFrom="opacity-100 translate-y-0 sm:scale-100"
                            leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        >
                            <Dialog.Panel className="relative transform overflow-hidden rounded-2xl bg-white dark:bg-zinc-900 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-2xl border border-zinc-200 dark:border-zinc-800">
                                <div className="absolute right-0 top-0 hidden pr-4 pt-4 sm:block">
                                    <button
                                        type="button"
                                        className="rounded-md bg-white dark:bg-zinc-900 text-zinc-400 hover:text-zinc-500 focus:outline-none"
                                        onClick={handleClose}
                                        disabled={loading}
                                    >
                                        <span className="sr-only">Fechar</span>
                                        <XMarkIcon className="h-6 w-6" aria-hidden="true" />
                                    </button>
                                </div>

                                <div className="p-6 sm:p-8">
                                    {/* Header */}
                                    <div className="sm:flex sm:items-start mb-6">
                                        <div className="mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900 sm:mx-0 sm:h-10 sm:w-10">
                                            <SparklesIcon className="h-6 w-6 text-blue-600 dark:text-blue-400" aria-hidden="true" />
                                        </div>
                                        <div className="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left">
                                            <Dialog.Title as="h3" className="text-xl font-semibold leading-6 text-zinc-900 dark:text-white">
                                                Criar Novo Plano
                                            </Dialog.Title>
                                            <div className="mt-2">
                                                <p className="text-sm text-zinc-500 dark:text-zinc-400">
                                                    Configure um novo plano de assinatura para as agências.
                                                </p>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Error Message */}
                                    {error && (
                                        <div className="mb-4 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 onSubmit={handleSubmit} className="space-y-4">
                                        {/* Row 1: Nome e Slug */}
                                        <div className="grid grid-cols-2 gap-4">
                                            <div>
                                                <label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
                                                    Nome do Plano *
                                                </label>
                                                <input
                                                    type="text"
                                                    name="name"
                                                    value={formData.name}
                                                    onChange={handleChange}
                                                    placeholder="Ex: Ignição"
                                                    className="w-full px-3 py-2 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"
                                                    required
                                                />
                                            </div>
                                            <div>
                                                <label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
                                                    Slug *
                                                </label>
                                                <input
                                                    type="text"
                                                    name="slug"
                                                    value={formData.slug}
                                                    onChange={handleChange}
                                                    placeholder="Ex: ignition"
                                                    className="w-full px-3 py-2 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"
                                                    required
                                                />
                                            </div>
                                        </div>

                                        {/* Descrição */}
                                        <div>
                                            <label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
                                                Descrição
                                            </label>
                                            <textarea
                                                name="description"
                                                value={formData.description}
                                                onChange={handleChange}
                                                placeholder="Descrição breve do plano"
                                                rows={2}
                                                className="w-full px-3 py-2 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 resize-none"
                                            />
                                        </div>

                                        {/* Row 2: Usuários */}
                                        <div className="grid grid-cols-2 gap-4">
                                            <div>
                                                <label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
                                                    Mín. Usuários
                                                </label>
                                                <input
                                                    type="number"
                                                    name="min_users"
                                                    value={formData.min_users}
                                                    onChange={handleChange}
                                                    min="1"
                                                    className="w-full px-3 py-2 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"
                                                />
                                            </div>
                                            <div>
                                                <label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
                                                    Máx. Usuários (-1 = ilimitado)
                                                </label>
                                                <input
                                                    type="number"
                                                    name="max_users"
                                                    value={formData.max_users}
                                                    onChange={handleChange}
                                                    className="w-full px-3 py-2 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"
                                                />
                                            </div>
                                        </div>

                                        {/* Row 3: Preços */}
                                        <div className="grid grid-cols-2 gap-4">
                                            <div>
                                                <label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
                                                    Preço Mensal (BRL)
                                                </label>
                                                <input
                                                    type="number"
                                                    name="monthly_price"
                                                    value={formData.monthly_price}
                                                    onChange={handleChange}
                                                    placeholder="199.99"
                                                    step="0.01"
                                                    className="w-full px-3 py-2 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"
                                                />
                                            </div>
                                            <div>
                                                <label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
                                                    Preço Anual (BRL)
                                                </label>
                                                <input
                                                    type="number"
                                                    name="annual_price"
                                                    value={formData.annual_price}
                                                    onChange={handleChange}
                                                    placeholder="1919.90"
                                                    step="0.01"
                                                    className="w-full px-3 py-2 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"
                                                />
                                            </div>
                                        </div>

                                        {/* Row 4: Storage */}
                                        <div>
                                            <label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
                                                Armazenamento (GB)
                                            </label>
                                            <input
                                                type="number"
                                                name="storage_gb"
                                                value={formData.storage_gb}
                                                onChange={handleChange}
                                                min="1"
                                                className="w-full px-3 py-2 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"
                                            />
                                        </div>

                                        {/* Row 5: Features */}
                                        <div>
                                            <label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
                                                Recursos <span className="text-xs text-zinc-500">(separados por vírgula)</span>
                                            </label>
                                            <textarea
                                                name="features"
                                                value={formData.features}
                                                onChange={handleChange}
                                                placeholder="CRM, ERP, Projetos, Helpdesk, Pagamentos, Contratos, Documentos"
                                                rows={2}
                                                className="w-full px-3 py-2 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 resize-none"
                                            />
                                        </div>

                                        {/* Row 6: Diferenciais */}
                                        <div>
                                            <label className="block text-sm font-medium text-zinc-900 dark:text-zinc-100 mb-1">
                                                Diferenciais <span className="text-xs text-zinc-500">(separados por vírgula)</span>
                                            </label>
                                            <textarea
                                                name="differentiators"
                                                value={formData.differentiators}
                                                onChange={handleChange}
                                                placeholder="Suporte prioritário, Gerente de conta dedicado, API integrações"
                                                rows={2}
                                                className="w-full px-3 py-2 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 resize-none"
                                            />
                                        </div>

                                        {/* Status Checkbox */}
                                        <div className="flex items-center pt-2">
                                            <input
                                                type="checkbox"
                                                name="is_active"
                                                checked={formData.is_active}
                                                onChange={handleChange}
                                                className="h-4 w-4 text-blue-600 rounded border-zinc-300 focus:ring-blue-500"
                                            />
                                            <label className="ml-3 text-sm font-medium text-zinc-900 dark:text-zinc-100">
                                                Plano Ativo
                                            </label>
                                        </div>

                                        {/* Buttons */}
                                        <div className="mt-6 pt-4 border-t border-zinc-200 dark:border-zinc-700 flex gap-3">
                                            <button
                                                type="submit"
                                                disabled={loading}
                                                className="flex-1 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors"
                                            >
                                                {loading ? 'Criando...' : 'Criar Plano'}
                                            </button>
                                            <button
                                                type="button"
                                                onClick={handleClose}
                                                disabled={loading}
                                                className="flex-1 px-4 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>
                                    </form>
                                </div>
                            </Dialog.Panel>
                        </Transition.Child>
                    </div>
                </div>
            </Dialog>
        </Transition.Root>
    );
}
