"use client";

import { useState } from "react";
import { useSettings, SettingItem } from "@/hooks/useSettings";
import { LuPlus, LuPencil, LuTrash2, LuSave, LuX } from "react-icons/lu";

interface ConfigOptionsModalProps {
    isOpen: boolean;
    onClose: () => void;
}

export default function ConfigOptionsModal({ isOpen, onClose }: ConfigOptionsModalProps) {
    const {
        expenseTypes,
        paymentMethods,
        isLoading,
        error,
        createExpenseType,
        updateExpenseType,
        deleteExpenseType,
        createPaymentMethod,
        updatePaymentMethod,
        deletePaymentMethod,
    } = useSettings();

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 bg-overlay z-50 flex items-center justify-center p-4">
            <div className="bg-background rounded-2xl shadow-2xl max-w-4xl w-full max-h-[90vh] flex flex-col overflow-hidden border border-border-subtle animate-scale-in">
                {/* Header */}
                <div className="flex items-center justify-between p-5 border-b border-border-subtle bg-background shrink-0">
                    <div>
                        <h2 className="text-xl font-bold text-text">Configuración de Opciones</h2>
                        <p className="text-sm text-text-muted">Administra los tipos de gasto y formas de pago globales.</p>
                    </div>
                    <button
                        onClick={onClose}
                        className="p-2 hover:bg-background-alt rounded-full transition-colors text-text-subtle hover:text-text focus-ring"
                    >
                        <LuX className="h-6 w-6" />
                    </button>
                </div>

                {/* Content */}
                <div className="p-6 overflow-y-auto flex-1">
                    {isLoading ? (
                        <div className="flex items-center justify-center py-12">
                            <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-primary"></div>
                        </div>
                    ) : error ? (
                        <div className="bg-destructive-background border border-destructive-border text-destructive-foreground px-4 py-3 rounded-lg text-sm mb-6">
                            {error}
                        </div>
                    ) : (
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                            {/* Tipos de Gasto */}
                            <SettingListSection
                                title="Tipos de Gasto"
                                items={expenseTypes}
                                onCreate={createExpenseType}
                                onUpdate={updateExpenseType}
                                onDelete={deleteExpenseType}
                                placeholder="Ej. Viáticos"
                            />

                            {/* Formas de Pago */}
                            <SettingListSection
                                title="Formas de Pago"
                                items={paymentMethods}
                                onCreate={createPaymentMethod}
                                onUpdate={updatePaymentMethod}
                                onDelete={deletePaymentMethod}
                                placeholder="Ej. Tarjeta de Crédito"
                            />
                        </div>
                    )}
                </div>

                {/* Footer */}
                <div className="p-4 border-t border-border-subtle bg-background-alt/30 flex justify-end">
                    <button
                        onClick={onClose}
                        className="px-6 py-2 bg-background border border-border text-text rounded-lg hover:bg-background-alt transition-colors font-medium focus-ring"
                    >
                        Cerrar
                    </button>
                </div>
            </div>
        </div>
    );
}

// Sub-componente para cada sección de lista
function SettingListSection({
    title,
    items,
    onCreate,
    onUpdate,
    onDelete,
    placeholder
}: {
    title: string;
    items: SettingItem[];
    onCreate: (name: string) => Promise<any>;
    onUpdate: (id: string, name: string) => Promise<any>;
    onDelete: (id: string) => Promise<any>;
    placeholder: string;
}) {
    const [newItemName, setNewItemName] = useState("");
    const [editingId, setEditingId] = useState<string | null>(null);
    const [editName, setEditName] = useState("");
    const [isSaving, setIsSaving] = useState(false);
    const [localError, setLocalError] = useState("");

    const handleCreate = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!newItemName.trim()) return;

        setIsSaving(true);
        setLocalError("");
        try {
            await onCreate(newItemName);
            setNewItemName("");
        } catch (err) {
            setLocalError(err instanceof Error ? err.message : "Error al crear");
        } finally {
            setIsSaving(false);
        }
    };

    const handleUpdate = async (id: string) => {
        if (!editName.trim()) return;

        setIsSaving(true);
        setLocalError("");
        try {
            await onUpdate(id, editName);
            setEditingId(null);
        } catch (err) {
            setLocalError(err instanceof Error ? err.message : "Error al actualizar");
        } finally {
            setIsSaving(false);
        }
    };

    const handleDelete = async (id: string) => {
        if (!confirm(`¿Estás seguro de eliminar esta opción?`)) return;

        setIsSaving(true);
        setLocalError("");
        try {
            await onDelete(id);
        } catch (err) {
            setLocalError(err instanceof Error ? err.message : "Error al eliminar");
        } finally {
            setIsSaving(false);
        }
    };

    return (
        <div className="flex flex-col h-full space-y-4">
            <h3 className="text-lg font-bold text-text border-b border-border-subtle pb-2">{title}</h3>
            
            {localError && (
                <div className="p-3 text-sm text-destructive bg-destructive-background border border-destructive-border rounded-lg">
                    {localError}
                </div>
            )}

            <div className="flex-1 space-y-2 min-h-[200px] max-h-[400px] overflow-y-auto pr-2 custom-scrollbar">
                {items.length === 0 ? (
                    <p className="text-center text-text-subtle py-10 italic">No hay opciones registradas.</p>
                ) : (
                    items.map(item => (
                        <div key={item.id} className="flex items-center justify-between p-3 bg-background-alt rounded-xl border border-border group hover:border-primary/30 transition-all">
                            {editingId === item.id ? (
                                <div className="flex-1 flex items-center gap-2">
                                    <input
                                        type="text"
                                        value={editName}
                                        onChange={(e) => setEditName(e.target.value)}
                                        className="flex-1 px-3 py-1.5 text-sm border border-primary rounded-lg focus:outline-none focus:ring-1 focus:ring-primary bg-background text-text"
                                        autoFocus
                                        onKeyDown={(e) => {
                                            if (e.key === "Enter") handleUpdate(item.id);
                                            if (e.key === "Escape") setEditingId(null);
                                        }}
                                    />
                                    <button
                                        onClick={() => handleUpdate(item.id)}
                                        disabled={isSaving}
                                        className="p-1.5 text-success hover:bg-success-background rounded-md transition-colors"
                                    >
                                        <LuSave className="h-4 w-4" />
                                    </button>
                                    <button
                                        onClick={() => setEditingId(null)}
                                        className="p-1.5 text-text-muted hover:bg-border-subtle rounded-md transition-colors"
                                    >
                                        <LuX className="h-4 w-4" />
                                    </button>
                                </div>
                            ) : (
                                <>
                                    <span className="text-sm font-medium text-text">{item.name}</span>
                                    <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                        <button
                                            onClick={() => {
                                                setEditingId(item.id);
                                                setEditName(item.name);
                                            }}
                                            className="p-1.5 text-text-subtle hover:text-primary hover:bg-primary-faint rounded-md transition-colors"
                                        >
                                            <LuPencil className="h-4 w-4" />
                                        </button>
                                        <button
                                            onClick={() => handleDelete(item.id)}
                                            disabled={isSaving}
                                            className="p-1.5 text-text-subtle hover:text-destructive hover:bg-destructive-background rounded-md transition-colors"
                                        >
                                            <LuTrash2 className="h-4 w-4" />
                                        </button>
                                    </div>
                                </>
                            )}
                        </div>
                    ))
                )}
            </div>

            <form onSubmit={handleCreate} className="flex gap-2 pt-2">
                <input
                    type="text"
                    value={newItemName}
                    onChange={(e) => setNewItemName(e.target.value)}
                    placeholder={placeholder}
                    className="flex-1 px-4 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent bg-background text-text placeholder-text-subtle transition-all"
                    disabled={isSaving}
                />
                <button
                    type="submit"
                    disabled={isSaving || !newItemName.trim()}
                    className="flex items-center justify-center gap-1.5 px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary-hover disabled:opacity-50 disabled:cursor-not-allowed transition-all text-sm font-semibold shadow-sm active:scale-95"
                >
                    <LuPlus className="h-4 w-4" />
                    Añadir
                </button>
            </form>
        </div>
    );
}
