import { useState, useEffect } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import PageHeader from '../../components/PageHeader';

/**
 * 🎨 MÓDULO: DISEÑO WEB - LISTADO
 * 
 * ✅ ESTILO ACTUALIZADO - Usa el diseño premium estándar
 */

interface Project {
    id: number;
    name: string;
    client_id?: number;
    client?: { id: number, name: string }; // Relación opcional para mostrar nombre
    status: 'discovery' | 'design' | 'development' | 'qa' | 'launched' | 'paused';
    start_date: string;
    due_date?: string;
    budget?: number;
}

interface Client {
    id: number;
    name: string;
}

const statusConfig: Record<string, { label: string; class: string; emoji: string }> = {
    discovery: { label: 'Descubrimiento', class: 'badge-purple', emoji: '🔍' },
    design: { label: 'Diseño', class: 'badge-primary', emoji: '🎨' },
    development: { label: 'Desarrollo', class: 'badge-warning', emoji: '💻' },
    qa: { label: 'QA / Testing', class: 'badge-orange', emoji: '🧪' },
    launched: { label: 'Lanzado', class: 'badge-success', emoji: '🚀' },
    paused: { label: 'Pausado', class: 'badge-default', emoji: '⏸️' },
};

export default function MobileDesignIndex() {
    const [projects, setProjects] = useState<Project[]>([]);
    const [clients, setClients] = useState<Client[]>([]);
    const [loading, setLoading] = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [submitting, setSubmitting] = useState(false);

    // Form State
    const [formData, setFormData] = useState({
        name: '',
        client_id: '',
        status: 'discovery',
        start_date: new Date().toISOString().split('T')[0], // Hoy por defecto
        due_date: '',
        budget: ''
    });

    useEffect(() => {
        fetchProjects();
        fetchClients();
    }, []);

    const fetchProjects = async () => {
        try {
            const res = await axios.get('/api/web-design/projects');
            setProjects(res.data);
        } catch (error) {
            console.error("Error cargando proyectos:", error);
        } finally {
            setLoading(false);
        }
    };

    const fetchClients = async () => {
        try {
            const res = await axios.get('/api/clients');
            // Asumiendo que la respuesta es paginada o lista directa, ajustamos si es necesario
            setClients(Array.isArray(res.data) ? res.data : res.data.data || []);
        } catch (error) {
            console.error("Error cargando clientes:", error);
        }
    };

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({ ...prev, [name]: value }));
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setSubmitting(true);
        try {
            await axios.post('/api/web-design/projects', {
                ...formData,
                client_id: formData.client_id ? parseInt(formData.client_id) : null,
                budget: formData.budget ? parseFloat(formData.budget) : null
            });
            setShowModal(false);
            fetchProjects(); // Recargar lista
            // Reset form
            setFormData({
                name: '',
                client_id: '',
                status: 'discovery',
                start_date: new Date().toISOString().split('T')[0],
                due_date: '',
                budget: ''
            });
        } catch (error) {
            console.error(error);
            alert('Error al crear el proyecto. Verifica los datos.');
        } finally {
            setSubmitting(false);
        }
    };

    const stats = [
        { icon: '🚀', label: 'Proyectos Activos', value: projects.filter(p => p.status !== 'launched' && p.status !== 'paused').length },
        { icon: '✅', label: 'Lanzados', value: projects.filter(p => p.status === 'launched').length },
    ];

    if (loading) return <div className="p-8 text-center text-slate-400">Cargando proyectos...</div>;

    return (
        <div className="animate-fadeIn">
            <PageHeader
                title="Proyectos de Diseño Web"
                subtitle="Gestión del ciclo de vida de desarrollo web"
                actions={
                    <button className="btn btn-primary" onClick={() => setShowModal(true)}>
                        🚀 Nuevo Proyecto
                    </button>
                }
                stats={stats}
            />

            <div className="table-container mt-6">
                <div className="table-header">
                    <h2 className="table-title">📑 Listado de Proyectos</h2>
                </div>
                <div className="table-wrapper">
                    <table className="table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Proyecto</th>
                                <th>Cliente</th>
                                <th>Etapa</th>
                                <th>Fecha Inicio</th>
                                <th>Entrega Estimada</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            {projects.length === 0 ? (
                                <tr>
                                    <td colSpan={7} className="text-center p-8 text-slate-500">
                                        No hay proyectos registrados. ¡Crea el primero!
                                    </td>
                                </tr>
                            ) : (
                                projects.map((project) => (
                                    <tr key={project.id}>
                                        <td className="text-slate-400 font-mono">#{project.id}</td>
                                        <td>
                                            <div className="font-bold text-white">{project.name}</div>
                                            {project.budget && <div className="text-xs text-slate-400">${project.budget}</div>}
                                        </td>
                                        <td className="text-sm">
                                            {/* Si tuviéramos la relación cargada mostraríamos nombre, por ahora ID o nombre manual */}
                                            {project.client_id ? `Cliente #${project.client_id}` : 'Interno'}
                                        </td>
                                        <td>
                                            <span className={`badge ${statusConfig[project.status]?.class || 'badge-default'}`}>
                                                {statusConfig[project.status]?.emoji} {statusConfig[project.status]?.label}
                                            </span>
                                        </td>
                                        <td>{project.start_date || '-'}</td>
                                        <td>{project.due_date || '-'}</td>
                                        <td>
                                            <Link to={`/app/web-design/projects/${project.id}`} className="btn btn-sm btn-ghost hover:text-blue-400">
                                                👁️ Gestionar
                                            </Link>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Modal Crear Proyecto - Estilo Marketing */}
            {showModal && (
                <div style={{
                    position: 'fixed',
                    inset: 0,
                    background: 'rgba(0, 0, 0, 0.7)',
                    backdropFilter: 'blur(4px)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 9999,
                    padding: '1rem'
                }} onClick={() => setShowModal(false)}>
                    <div className="card" style={{
                        maxWidth: '600px',
                        width: '100%',
                        maxHeight: '90vh',
                        overflowY: 'auto'
                    }} onClick={(e) => e.stopPropagation()}>
                        <div style={{ padding: '1.5rem', borderBottom: '1px solid var(--border-color)' }}>
                            <h2 style={{ fontSize: '1.5rem', fontWeight: 700, color: 'var(--text-primary)' }}>
                                🎨 Nuevo Proyecto
                            </h2>
                            <p style={{ fontSize: '0.9rem', color: 'var(--text-muted)', marginTop: '0.5rem' }}>
                                Crea un nuevo proyecto de diseño web
                            </p>
                        </div>
                        <form onSubmit={handleSubmit} style={{ padding: '1.5rem' }}>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Nombre del proyecto
                                    </label>
                                    <input
                                        type="text"
                                        name="name"
                                        className="input"
                                        value={formData.name}
                                        onChange={handleInputChange}
                                        required
                                        placeholder="Ej: Rediseño Sitio Corporativo"
                                    />
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Cliente
                                    </label>
                                    <select
                                        name="client_id"
                                        className="input"
                                        value={formData.client_id}
                                        onChange={handleInputChange}
                                    >
                                        <option value="">Seleccionar cliente</option>
                                        {clients.map(client => (
                                            <option key={client.id} value={client.id}>{client.name}</option>
                                        ))}
                                    </select>
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Estado
                                    </label>
                                    <select
                                        name="status"
                                        className="input"
                                        value={formData.status}
                                        onChange={handleInputChange}
                                    >
                                        {Object.entries(statusConfig).map(([key, config]) => (
                                            <option key={key} value={key}>{config.emoji} {config.label}</option>
                                        ))}
                                    </select>
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Presupuesto
                                    </label>
                                    <input
                                        type="number"
                                        name="budget"
                                        className="input"
                                        value={formData.budget}
                                        onChange={handleInputChange}
                                        placeholder="0.00"
                                        step="0.01"
                                    />
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Fecha de inicio
                                    </label>
                                    <input
                                        type="date"
                                        name="start_date"
                                        className="input"
                                        value={formData.start_date}
                                        onChange={handleInputChange}
                                    />
                                </div>
                                <div>
                                    <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 500 }}>
                                        Entrega estimada
                                    </label>
                                    <input
                                        type="date"
                                        name="due_date"
                                        className="input"
                                        value={formData.due_date}
                                        onChange={handleInputChange}
                                    />
                                </div>
                                <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end', marginTop: '1rem' }}>
                                    <button
                                        type="button"
                                        className="btn btn-secondary"
                                        onClick={() => setShowModal(false)}
                                    >
                                        Cancelar
                                    </button>
                                    <button
                                        type="submit"
                                        className="btn btn-primary"
                                        disabled={submitting}
                                    >
                                        {submitting ? 'Creando...' : '✨ Crear Proyecto'}
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
