import { Head } from '@inertiajs/react';
import Layout from '../../../Layouts';
import { Container, Row, Col } from 'react-bootstrap';
import { useLoading } from '../../../LoadingContext';
import ClientSearchInput from './Components/ClientSearchInput';
import ClientDetailPanel from './Components/ClientDetailPanel';
import CardSectionStatus from './Components/CardSectionStatus';
import { Users, Search, ArrowLeft, Building2 } from 'lucide-react';
import { useClienteDashboardData } from './hooks/useClienteDashboardData';
import './Dashboard.css';

export default function Dashboard() {
    const {
        clientes,
        selectedCliente,
        loading,
        detailLoading,
        detailError,
        setSelectedCliente,
        handleSearch,
        refreshSelectedCliente,
        retryDetalle,
    } = useClienteDashboardData();

    const { showLoading, hideLoading } = useLoading();

    const handleSelectCliente = async (cliente: any) => {
        setSelectedCliente(cliente);
        await refreshSelectedCliente(cliente.CodCli);
    };

    const handleBackToResults = () => {
        setSelectedCliente(null);
    };

    return (
        <Layout>
            <Head title="Ficha de Cliente — Dashboard" />
            <div className="page-content dashboard-shell">
                <Container fluid className="pt-1 pb-4 px-1 px-md-2" style={{ maxWidth: '100%' }}>                    
                    {/* Área de Búsqueda */}
                    {!selectedCliente && (
                        <div className="mb-4 text-center">
                            <div className="d-inline-flex align-items-center gap-2 px-3 py-1 rounded-pill mb-3" style={{ background: '#eff6ff', border: '1px solid #dbeafe', color: '#2563eb', fontSize: '0.75rem', fontWeight: 600 }}>
                                <Building2 size={13} />
                                <span>Directorio Centralizado</span>
                            </div>
                            <h2 className="saas-title mb-2" style={{ fontSize: '1.75rem' }}>
                                Gestión de Clientes y Suministros
                            </h2>
                            <p style={{ fontSize: '0.875rem', color: '#64748b', maxWidth: '460px', margin: '0 auto 1.25rem' }}>
                                Localiza rápidamente cualquier cliente para consultar o gestionar contratos, suministros, bancos y documentación.
                            </p>
                            <ClientSearchInput 
                                onSearch={handleSearch} 
                                isLoading={loading} 
                                placeholder="Buscar cliente por Razón Social, CIF/NIF o Contacto..."
                            />
                        </div>
                    )}

                    {/* Resultados de Búsqueda */}
                    {!selectedCliente && (
                        <div>
                            {loading ? (
                                <div className="text-center py-5">
                                    <div className="spinner-border text-primary mb-2" role="status"></div>
                                    <p style={{ fontSize: '0.875rem', color: '#64748b' }}>Buscando clientes...</p>
                                </div>
                            ) : clientes.length > 0 ? (
                                <Row className="g-3">
                                    {clientes.map((cli) => (
                                        <Col xs={12} md={6} lg={4} key={cli.CodCli}>
                                            <div 
                                                className="saas-card saas-card-hover p-3 d-flex align-items-center gap-3 cursor-pointer"
                                                onClick={() => handleSelectCliente(cli)}
                                                style={{ cursor: 'pointer' }}
                                            >
                                                <div className="saas-icon-badge primary" style={{ width: '42px', height: '42px', borderRadius: '10px' }}>
                                                    <Users size={20} />
                                                </div>
                                                <div className="text-truncate flex-grow-1">
                                                    <h4 className="m-0 text-truncate" style={{ fontSize: '0.875rem', fontWeight: 700, color: '#0f172a' }}>
                                                        {cli.RazSocCli}
                                                    </h4>
                                                    <div className="d-flex align-items-center gap-2 mt-1" style={{ fontSize: '0.75rem', color: '#64748b' }}>
                                                        <span style={{ fontFamily: 'monospace', fontWeight: 700, color: '#334155' }}>{cli.NumCifCli}</span>
                                                        <span>•</span>
                                                        <span className="text-truncate">{cli.EmaCli || 'Sin email'}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </Col>
                                    ))}
                                </Row>
                            ) : (
                                <div className="text-center py-5">
                                    <div className="saas-empty-icon mx-auto mb-3" style={{ width: '54px', height: '54px' }}>
                                        <Search size={24} />
                                    </div>
                                    <h4 style={{ fontSize: '1rem', fontWeight: 700, color: '#1e293b', marginBottom: '0.25rem' }}>
                                        Encuentra o selecciona un cliente
                                    </h4>
                                    <p style={{ fontSize: '0.8125rem', color: '#94a3b8', maxWidth: '380px', margin: '0 auto' }}>
                                        Escribe al menos 3 caracteres de la razón social, nombre o CIF para consultar su ficha técnica.
                                    </p>
                                </div>
                            )}
                        </div>
                    )}

                    {/* Detalle del Cliente Seleccionado */}
                    {selectedCliente && (
                        <div>
                            <div className="d-flex justify-content-between align-items-center mb-2">
                                <button 
                                    type="button"
                                    className="saas-btn-outline"
                                    onClick={handleBackToResults}
                                >
                                    <ArrowLeft size={14} /> 
                                    <span>Volver a la búsqueda</span>
                                </button>
                                <span style={{ fontSize: '0.6875rem', fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                                    Ficha Integral de Cliente
                                </span>
                            </div>

                            <CardSectionStatus
                                isLoading={detailLoading && !detailError}
                                error={detailError}
                                onRetry={retryDetalle}
                            >
                                <ClientDetailPanel
                                    cliente={selectedCliente}
                                    refreshData={refreshSelectedCliente}
                                    loading={{
                                        show: showLoading,
                                        hide: hideLoading
                                    }}
                                />
                            </CardSectionStatus>
                        </div>
                    )}
                </Container>
            </div>
        </Layout>
    );
}
