import { useState, useMemo, CSSProperties } from 'react';
import PageHeader from '../components/PageHeader';

interface Client {
    id: number;
    name: string;
    email: string;
    phone: string;
    company: string;
    status: 'active' | 'inactive' | 'lead';
    services_count: number;
    total_revenue: number;
    last_service_date: string;
    notes: string;
}

/**
 * 👥 PÁGINA: CLIENTES
 * 
 * ✅ ESTILO ACTUALIZADO - Usa el diseño premium estándar
 */

// Mock data - Ready for MariaDB connection
const mockClients: Client[] = [
    { id: 1, name: 'Juan García', email: 'juan@acme.com', phone: '+58 412 1234567', company: 'Acme Corporation', status: 'active', services_count: 5, total_revenue: 2450.00, last_service_date: '2026-01-15', notes: 'Cliente premium desde 2023' },
    { id: 2, name: 'María Rodríguez', email: 'maria@betatech.com', phone: '+58 414 7654321', company: 'Beta Technologies', status: 'active', services_count: 3, total_revenue: 1890.00, last_service_date: '2026-01-10', notes: 'Interesado en más servicios de hosting' },
    { id: 3, name: 'Carlos López', email: 'carlos@gamma.com', phone: '+58 416 9876543', company: 'Gamma Retail SA', status: 'inactive', services_count: 1, total_revenue: 450.00, last_service_date: '2025-06-20', notes: 'Dominio vencido, pendiente renovación' },
    { id: 4, name: 'Ana Martínez', email: 'ana@delta.com', phone: '+58 424 1112223', company: 'Delta Industries', status: 'lead', services_count: 0, total_revenue: 0, last_service_date: '', notes: 'Prospecto - contactar para propuesta' },
    { id: 5, name: 'Roberto Fernández', email: 'roberto@epsilon.net', phone: '+58 412 3334445', company: 'Epsilon Tech', status: 'active', services_count: 4, total_revenue: 3200.00, last_service_date: '2026-01-22', notes: 'Desarrollo web en curso' },
    { id: 6, name: 'Laura Gómez', email: 'laura@zetamedia.io', phone: '+58 414 5556667', company: 'Zeta Media', status: 'active', services_count: 2, total_revenue: 780.00, last_service_date: '2025-12-05', notes: '' },
    { id: 7, name: 'Pedro Sánchez', email: 'pedro@omega.co', phone: '+58 416 7778889', company: 'Omega Solutions', status: 'inactive', services_count: 1, total_revenue: 120.00, last_service_date: '2025-03-10', notes: 'Servicio cancelado' },
    { id: 8, name: 'Carmen Díaz', email: 'carmen@sigma.com', phone: '+58 424 9990001', company: 'Sigma Corp', status: 'active', services_count: 3, total_revenue: 1560.00, last_service_date: '2026-01-20', notes: 'Renovación mensual de soporte' },
];

const statusConfig: Record<string, { label: string; class: string; color: string }> = {
    active: { label: 'Activo', class: 'badge-success', color: '#10b981' },
    inactive: { label: 'Inactivo', class: 'badge-default', color: '#64748b' },
    lead: { label: 'Prospecto', class: 'badge-warning', color: '#f59e0b' },
};

export default function Clients() {
    const [clients, setClients] = useState<Client[]>(mockClients);
    const [search, setSearch] = useState('');
    const [filterStatus, setFilterStatus] = useState<string>('all');
    const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid');
    const [showAddModal, setShowAddModal] = useState(false);
    const [showEditModal, setShowEditModal] = useState(false);
    const [editingClient, setEditingClient] = useState<Client | null>(null);
    const [_selectedClient, setSelectedClient] = useState<Client | null>(null);

    // Handle opening edit modal
    const handleEditClient = (client: Client, e: React.MouseEvent) => {
        e.stopPropagation();
        setEditingClient({ ...client });
        setShowEditModal(true);
    };

    // Handle saving edited client
    const handleSaveEdit = () => {
        if (editingClient) {
            setClients(prevClients =>
                prevClients.map(c =>
                    c.id === editingClient.id ? editingClient : c
                )
            );
            setShowEditModal(false);
            setEditingClient(null);
        }
    };

    // Handle edit form field change
    const handleEditFieldChange = (field: keyof Client, value: string) => {
        if (editingClient) {
            setEditingClient({
                ...editingClient,
                [field]: value
            });
        }
    };

    const filteredClients = useMemo(() => {
        return clients.filter(client => {
            const matchSearch = client.name.toLowerCase().includes(search.toLowerCase()) ||
                client.email.toLowerCase().includes(search.toLowerCase()) ||
                client.company.toLowerCase().includes(search.toLowerCase());
            const matchStatus = filterStatus === 'all' || client.status === filterStatus;
            return matchSearch && matchStatus;
        });
    }, [clients, search, filterStatus]);

    // Stats
    const stats = useMemo(() => ({
        total: clients.length,
        active: clients.filter(c => c.status === 'active').length,
        inactive: clients.filter(c => c.status === 'inactive').length,
        leads: clients.filter(c => c.status === 'lead').length,
        totalRevenue: clients.reduce((sum, c) => sum + c.total_revenue, 0),
    }), [clients]);

    const metricCards = [
        {
            icon: '👥',
            label: 'Total Clientes',
            value: stats.total.toString(),
            subtext: `${stats.active} activos`,
            gradient: 'linear-gradient(135deg, #8b5cf6, #7c3aed)',
            glow: 'rgba(139, 92, 246, 0.4)',
        },
        {
            icon: '✅',
            label: 'Clientes Activos',
            value: stats.active.toString(),
            gradient: 'linear-gradient(135deg, #10b981, #059669)',
            glow: 'rgba(16, 185, 129, 0.4)',
        },
        {
            icon: '🎯',
            label: 'Prospectos',
            value: stats.leads.toString(),
            gradient: 'linear-gradient(135deg, #f59e0b, #d97706)',
            glow: 'rgba(245, 158, 11, 0.4)',
        },
        {
            icon: '💰',
            label: 'Ingresos Totales',
            value: `$${stats.totalRevenue.toLocaleString('es-ES', { minimumFractionDigits: 2 })}`,
            gradient: 'linear-gradient(135deg, #3b82f6, #2563eb)',
            glow: 'rgba(59, 130, 246, 0.4)',
        },
    ];

    return (
        <div className="animate-fadeIn">
            {/* Page Header - Componente estándar */}
            <PageHeader
                title="Clientes"
                subtitle="Gestiona tu cartera de clientes"
                actions={
                    <>
                        <button
                            className={`btn ${viewMode === 'grid' ? 'btn-primary' : 'btn-secondary'}`}
                            onClick={() => setViewMode('grid')}
                        >
                            ⊞ Grid
                        </button>
                        <button
                            className={`btn ${viewMode === 'table' ? 'btn-primary' : 'btn-secondary'}`}
                            onClick={() => setViewMode('table')}
                        >
                            ☰ Tabla
                        </button>
                        <button className="btn btn-primary" onClick={() => setShowAddModal(true)}>
                            ➕ Nuevo Cliente
                        </button>
                    </>
                }
                stats={[
                    { icon: '📅', label: 'Hoy', value: new Date().toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'short' }) },
                    { icon: '📊', label: 'Total clientes', value: stats.total },
                ]}
            />

            {/* Metric Cards Grid - Mismo estilo del Dashboard */}
            <div className="cards-grid">
                {metricCards.map((card, index) => (
                    <div
                        key={index}
                        className="card metric-card"
                        style={{ '--card-glow': card.glow } as CSSProperties}
                    >
                        <div
                            className="metric-icon"
                            style={{ background: card.gradient }}
                        >
                            {card.icon}
                        </div>
                        <div className="metric-content">
                            <div className="metric-label">{card.label}</div>
                            <div className="metric-value">{card.value}</div>
                            {card.subtext && (
                                <div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginTop: '0.25rem' }}>
                                    {card.subtext}
                                </div>
                            )}
                        </div>
                    </div>
                ))}
            </div>

            {/* Filters */}
            <div className="filters">
                <div className="form-group" style={{ marginBottom: 0, flex: 1, maxWidth: '350px' }}>
                    <input
                        type="text"
                        className="form-input"
                        placeholder="🔍 Buscar por nombre, email o empresa..."
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                    />
                </div>

                <select
                    className="form-select"
                    value={filterStatus}
                    onChange={(e) => setFilterStatus(e.target.value)}
                    style={{ minWidth: '150px' }}
                >
                    <option value="all">Todos los estados</option>
                    <option value="active">✅ Activos</option>
                    <option value="inactive">⏸️ Inactivos</option>
                    <option value="lead">🎯 Prospectos</option>
                </select>

                {(search || filterStatus !== 'all') && (
                    <button
                        className="btn btn-ghost btn-sm"
                        onClick={() => { setSearch(''); setFilterStatus('all'); }}
                    >
                        ✕ Limpiar filtros
                    </button>
                )}
            </div>

            {/* Content */}
            {filteredClients.length === 0 ? (
                <div className="card">
                    <div className="empty-state">
                        <div className="empty-state-icon">👥</div>
                        <div className="empty-state-title">No hay clientes</div>
                        <div className="empty-state-text">
                            No se encontraron clientes con los filtros actuales
                        </div>
                        <button
                            className="btn btn-secondary"
                            style={{ marginTop: '1rem' }}
                            onClick={() => { setSearch(''); setFilterStatus('all'); }}
                        >
                            Limpiar filtros
                        </button>
                    </div>
                </div>
            ) : viewMode === 'grid' ? (
                /* Grid View */
                <div className="cards-grid" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))' }}>
                    {filteredClients.map((client) => (
                        <div
                            key={client.id}
                            className="card"
                            style={{ cursor: 'pointer' }}
                            onClick={() => setSelectedClient(client)}
                        >
                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '1rem', marginBottom: '1rem' }}>
                                <div style={{
                                    width: '52px',
                                    height: '52px',
                                    borderRadius: '14px',
                                    background: `linear-gradient(135deg, ${statusConfig[client.status].color}40, ${statusConfig[client.status].color}20)`,
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    color: statusConfig[client.status].color,
                                    fontWeight: 700,
                                    fontSize: '1.1rem',
                                }}>
                                    {client.name.split(' ').map(n => n[0]).join('').substring(0, 2)}
                                </div>
                                <div style={{ flex: 1 }}>
                                    <div style={{ fontWeight: 600, fontSize: '1.05rem', marginBottom: '0.25rem' }}>
                                        {client.name}
                                    </div>
                                    <div style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>
                                        🏢 {client.company}
                                    </div>
                                </div>
                                <span className={`badge ${statusConfig[client.status]?.class || 'badge-default'}`}>
                                    <span className="badge-dot"></span>
                                    {statusConfig[client.status]?.label || client.status}
                                </span>
                            </div>

                            <div style={{
                                fontSize: '0.875rem',
                                color: 'var(--text-secondary)',
                                display: 'flex',
                                flexDirection: 'column',
                                gap: '0.5rem',
                            }}>
                                <div>📧 {client.email}</div>
                                <div>📱 {client.phone}</div>
                            </div>

                            <div style={{
                                display: 'grid',
                                gridTemplateColumns: 'repeat(3, 1fr)',
                                gap: '0.75rem',
                                marginTop: '1rem',
                                paddingTop: '1rem',
                                borderTop: '1px solid var(--border-color)',
                            }}>
                                <div style={{ textAlign: 'center' }}>
                                    <div style={{ fontSize: '1.25rem', fontWeight: 700, color: 'var(--text-primary)' }}>
                                        {client.services_count}
                                    </div>
                                    <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)', textTransform: 'uppercase' }}>
                                        Servicios
                                    </div>
                                </div>
                                <div style={{ textAlign: 'center' }}>
                                    <div style={{ fontSize: '1.25rem', fontWeight: 700, color: 'var(--color-success)' }}>
                                        ${client.total_revenue.toLocaleString('es-ES')}
                                    </div>
                                    <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)', textTransform: 'uppercase' }}>
                                        Ingresos
                                    </div>
                                </div>
                                <div style={{ textAlign: 'center' }}>
                                    <div style={{ fontSize: '0.9rem', fontWeight: 600, color: 'var(--text-primary)' }}>
                                        {client.last_service_date
                                            ? new Date(client.last_service_date).toLocaleDateString('es-ES', { day: '2-digit', month: 'short' })
                                            : '—'
                                        }
                                    </div>
                                    <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)', textTransform: 'uppercase' }}>
                                        Último Serv.
                                    </div>
                                </div>
                            </div>

                            <div style={{
                                display: 'flex',
                                gap: '0.5rem',
                                marginTop: '1rem',
                            }}>
                                <button className="btn btn-secondary btn-sm" style={{ flex: 1 }}>
                                    👁️ Ver detalles
                                </button>
                                <button className="btn-icon" style={{ width: '36px', height: '36px' }} onClick={(e) => handleEditClient(client, e)}>✏️</button>
                                <button className="btn-icon" style={{ width: '36px', height: '36px' }}>📧</button>
                            </div>
                        </div>
                    ))}
                </div>
            ) : (
                /* Table View */
                <div className="table-container">
                    <div className="table-wrapper">
                        <table className="table">
                            <thead>
                                <tr>
                                    <th>Cliente</th>
                                    <th>Empresa</th>
                                    <th>Contacto</th>
                                    <th>Servicios</th>
                                    <th>Ingresos</th>
                                    <th>Último Servicio</th>
                                    <th>Estado</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                {filteredClients.map((client) => (
                                    <tr key={client.id}>
                                        <td>
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                                                <div style={{
                                                    width: '40px',
                                                    height: '40px',
                                                    borderRadius: '10px',
                                                    background: `linear-gradient(135deg, ${statusConfig[client.status].color}40, ${statusConfig[client.status].color}20)`,
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    justifyContent: 'center',
                                                    color: statusConfig[client.status].color,
                                                    fontWeight: 700,
                                                    fontSize: '0.85rem',
                                                }}>
                                                    {client.name.split(' ').map(n => n[0]).join('').substring(0, 2)}
                                                </div>
                                                <div className="cell-main">{client.name}</div>
                                            </div>
                                        </td>
                                        <td>{client.company}</td>
                                        <td>
                                            <div style={{ fontSize: '0.85rem' }}>{client.email}</div>
                                            <div className="cell-secondary">{client.phone}</div>
                                        </td>
                                        <td>
                                            <span style={{
                                                fontWeight: 700,
                                                color: client.services_count > 0 ? 'var(--text-primary)' : 'var(--text-muted)'
                                            }}>
                                                {client.services_count}
                                            </span>
                                        </td>
                                        <td>
                                            <span style={{ fontWeight: 600, color: 'var(--color-success)' }}>
                                                ${client.total_revenue.toLocaleString('es-ES', { minimumFractionDigits: 2 })}
                                            </span>
                                        </td>
                                        <td>
                                            {client.last_service_date
                                                ? new Date(client.last_service_date).toLocaleDateString('es-ES', {
                                                    day: '2-digit',
                                                    month: 'short',
                                                    year: '2-digit'
                                                })
                                                : '—'
                                            }
                                        </td>
                                        <td>
                                            <span className={`badge ${statusConfig[client.status]?.class}`}>
                                                <span className="badge-dot"></span>
                                                {statusConfig[client.status]?.label}
                                            </span>
                                        </td>
                                        <td>
                                            <div style={{ display: 'flex', gap: '0.5rem' }}>
                                                <button className="btn-icon" title="Ver" style={{ width: '36px', height: '36px' }}>👁️</button>
                                                <button className="btn-icon" title="Editar" style={{ width: '36px', height: '36px' }} onClick={(e) => handleEditClient(client, e)}>✏️</button>
                                                <button className="btn-icon" title="Email" style={{ width: '36px', height: '36px' }}>📧</button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}

            {/* Results Count */}
            <div style={{
                marginTop: '1rem',
                fontSize: '0.85rem',
                color: 'var(--text-muted)',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
            }}>
                <span>Mostrando {filteredClients.length} de {clients.length} clientes</span>
                <button className="btn btn-ghost btn-sm">📥 Exportar</button>
            </div>

            {/* Add Client Modal */}
            {showAddModal && (
                <div className="modal-overlay" onClick={() => setShowAddModal(false)}>
                    <div className="modal" onClick={e => e.stopPropagation()}>
                        <div className="modal-header">
                            <h2 className="modal-title">Nuevo Cliente</h2>
                            <button className="modal-close" onClick={() => setShowAddModal(false)}>✕</button>
                        </div>

                        <form>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                                <div className="form-group">
                                    <label className="form-label">Nombre completo *</label>
                                    <input type="text" className="form-input" placeholder="Juan García" />
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Empresa</label>
                                    <input type="text" className="form-input" placeholder="Acme Corp" />
                                </div>
                            </div>

                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                                <div className="form-group">
                                    <label className="form-label">Email *</label>
                                    <input type="email" className="form-input" placeholder="email@empresa.com" />
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Teléfono</label>
                                    <input type="tel" className="form-input" placeholder="+58 412 1234567" />
                                </div>
                            </div>

                            <div className="form-group">
                                <label className="form-label">Estado</label>
                                <select className="form-select">
                                    <option value="lead">🎯 Prospecto</option>
                                    <option value="active">✅ Activo</option>
                                    <option value="inactive">⏸️ Inactivo</option>
                                </select>
                            </div>

                            <div className="form-group">
                                <label className="form-label">Notas</label>
                                <textarea
                                    className="form-input"
                                    rows={3}
                                    placeholder="Notas adicionales sobre el cliente..."
                                />
                            </div>
                        </form>

                        <div className="modal-footer">
                            <button className="btn btn-secondary" onClick={() => setShowAddModal(false)}>
                                Cancelar
                            </button>
                            <button className="btn btn-primary">
                                💾 Guardar Cliente
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Edit Client Modal */}
            {showEditModal && editingClient && (
                <div className="modal-overlay" onClick={() => { setShowEditModal(false); setEditingClient(null); }}>
                    <div className="modal" onClick={e => e.stopPropagation()}>
                        <div className="modal-header">
                            <h2 className="modal-title">✏️ Editar Cliente</h2>
                            <button className="modal-close" onClick={() => { setShowEditModal(false); setEditingClient(null); }}>✕</button>
                        </div>

                        <form onSubmit={(e) => { e.preventDefault(); handleSaveEdit(); }}>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                                <div className="form-group">
                                    <label className="form-label">Nombre completo *</label>
                                    <input
                                        type="text"
                                        className="form-input"
                                        value={editingClient.name}
                                        onChange={(e) => handleEditFieldChange('name', e.target.value)}
                                        required
                                    />
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Empresa</label>
                                    <input
                                        type="text"
                                        className="form-input"
                                        value={editingClient.company}
                                        onChange={(e) => handleEditFieldChange('company', e.target.value)}
                                    />
                                </div>
                            </div>

                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                                <div className="form-group">
                                    <label className="form-label">Email *</label>
                                    <input
                                        type="email"
                                        className="form-input"
                                        value={editingClient.email}
                                        onChange={(e) => handleEditFieldChange('email', e.target.value)}
                                        required
                                    />
                                </div>

                                <div className="form-group">
                                    <label className="form-label">Teléfono</label>
                                    <input
                                        type="tel"
                                        className="form-input"
                                        value={editingClient.phone}
                                        onChange={(e) => handleEditFieldChange('phone', e.target.value)}
                                    />
                                </div>
                            </div>

                            <div className="form-group">
                                <label className="form-label">Estado</label>
                                <select
                                    className="form-select"
                                    value={editingClient.status}
                                    onChange={(e) => handleEditFieldChange('status', e.target.value)}
                                >
                                    <option value="lead">🎯 Prospecto</option>
                                    <option value="active">✅ Activo</option>
                                    <option value="inactive">⏸️ Inactivo</option>
                                </select>
                            </div>

                            <div className="form-group">
                                <label className="form-label">Notas</label>
                                <textarea
                                    className="form-input"
                                    rows={3}
                                    value={editingClient.notes}
                                    onChange={(e) => handleEditFieldChange('notes', e.target.value)}
                                    placeholder="Notas adicionales sobre el cliente..."
                                />
                            </div>
                        </form>

                        <div className="modal-footer">
                            <button className="btn btn-secondary" onClick={() => { setShowEditModal(false); setEditingClient(null); }}>
                                Cancelar
                            </button>
                            <button className="btn btn-primary" onClick={handleSaveEdit}>
                                💾 Guardar Cambios
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
