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

export default function Dashboard() {
    const { clientes, selectedCliente, loading, setSelectedCliente, handleSearch, refreshSelectedCliente } =
        useClienteDashboardData();
    
    // Contexto de carga global (para operaciones pesadas)
    const { showLoading, hideLoading } = useLoading();

    // Al seleccionar un cliente de la lista
    const handleSelectCliente = async (cliente: any) => {
        setSelectedCliente(cliente);
        await refreshSelectedCliente(cliente.CodCli).catch(() => null);
    };

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

    return (
        <Layout>
            <Head title="Dashboard Eneon" />
            <div className="page-content min-vh-100 dashboard-shell">
                <Container fluid className="pt-4 pb-5">                    
                    <Row className="justify-content-center">
                        <Col xs={12}>
                            {/* Área de Búsqueda */}
                            {!selectedCliente && (
                                <div className="mb-4 fade-in-down">
                                    <ClientSearchInput 
                                        onSearch={handleSearch} 
                                        isLoading={loading} 
                                        placeholder="Buscar cliente por Nombre, CIF/NIF..."
                                    />
                                </div>
                            )}

                            {/* Resultados de Búsqueda */}
                            {!selectedCliente && (
                                <div className="search-results-container fade-in-up">
                                    {loading ? (
                                        <div className="text-center py-5">
                                            <Spinner animation="border" variant="primary" />
                                            <p className="mt-2 text-muted">Buscando clientes...</p>
                                        </div>
                                    ) : clientes.length > 0 ? (
                                        <Row className="g-3">
                                            {clientes.map((cli) => (
                                                <Col xs={12} md={6} key={cli.CodCli}>
                                                    <Card 
                                                        className="h-100 cursor-pointer hover-card transition-all dashboard-card dashboard-gradient-a"
                                                        onClick={() => handleSelectCliente(cli)}
                                                    >
                                                        <Card.Body className="d-flex align-items-center p-3">
                                                            <div className="avatar bg-soft-primary text-primary rounded-circle p-3 me-3">
                                                                <Users size={24} />
                                                            </div>
                                                            <div>
                                                                <h6 className="fw-bold mb-1 text-dark">{cli.RazSocCli}</h6>
                                                                <div className="small text-muted mb-1">CIF: {cli.NumCifCli}</div>
                                                                <div className="small text-muted">{cli.EmaCli || 'Sin email'}</div>
                                                            </div>
                                                        </Card.Body>
                                                    </Card>
                                                </Col>
                                            ))}
                                        </Row>
                                    ) : (
                                        // Empty State
                                        <div className="text-center py-5 opacity-50">
                                            <div className="mb-3">
                                                <Search size={48} className="text-muted" />
                                            </div>
                                            <h5 className="text-muted">Busca un cliente para comenzar</h5>
                                            <p className="small text-muted">Ingresa el nombre o CIF del cliente</p>
                                        </div>
                                    )}
                                </div>
                            )}

                            {/* Detalle del Cliente Seleccionado */}
                            {selectedCliente && (
                                <div className="client-detail-wrapper">
                                    <div className="d-flex justify-content-between align-items-center mb-3">
                                        <Button 
                                            variant="link" 
                                            className="p-0 text-decoration-none text-muted hover-primary"
                                            onClick={handleBackToResults}
                                        >
                                            &larr; Volver a resultados
                                        </Button>
                                        <h5 className="dashboard-title mb-0">Gestión de Clientes y Suministros</h5>
                                    </div>

                                    <ClientDetailPanel 
                                        cliente={selectedCliente}
                                        refreshData={refreshSelectedCliente}
                                        loading={{
                                            show: showLoading,
                                            hide: hideLoading
                                        }}
                                    />
                                </div>
                            )}
                        </Col>
                    </Row>
                </Container>
            </div>
        </Layout>
    );
}
