import React, { useState } from 'react';
import { Badge, Button, Card, Col, Row, Form } from 'react-bootstrap';
import { Building, CreditCard, Edit, FileText, MapPin, Plus, Zap, Flame, Users } from 'lucide-react';
import DocumentoCard from '../DocumentoCard';
import EditarClienteModal from '../Editar/EditarClienteModal';
import EditarContactoModal from '../Editar/EditarContactoModal';
import EditarCuentaBancariaModal from '../Editar/EditarCuentaBancariaModal';
import EditarPuntoSuministroModal from '../Editar/EditarPuntoSuministroModal';
import CrearContactoModal from '../Editar/CrearContactoModal';
import CrearCuentaBancariaModal from '../Editar/CrearCuentaBancariaModal';
import CrearPuntoSuministroModal from '../Editar/CrearPuntoSuministroModal';
import SubirDocumentoModal from '../Editar/SubirDocumentoModal';
import { DashboardCliente } from '../types';
import axios from 'axios';
import Swal from 'sweetalert2';

interface ClientDetailPanelProps {
    cliente: DashboardCliente;
    refreshData: () => Promise<void>;
    loading: { show: () => void; hide: () => void };
}

const ClientDetailPanel: React.FC<ClientDetailPanelProps> = ({ cliente, refreshData, loading }) => {
    // Modal states
    if (import.meta.env.DEV) console.log('[ClientDetailPanel] cliente', cliente);
    const [showEditarModal, setShowEditarModal] = useState(false);
    const [showEditarContactoModal, setShowEditarContactoModal] = useState(false);
    const [showEditarCuentaModal, setShowEditarCuentaModal] = useState(false);
    const [showEditarPuntoModal, setShowEditarPuntoModal] = useState(false);
    const [showCrearContactoModal, setShowCrearContactoModal] = useState(false);
    const [showCrearCuentaModal, setShowCrearCuentaModal] = useState(false);
    const [showCrearPuntoModal, setShowCrearPuntoModal] = useState(false);
    const [showSubirDocumentoModal, setShowSubirDocumentoModal] = useState(false);
    const [cuentaEdit, setCuentaEdit] = useState<any>(null);
    const [puntoEdit, setPuntoEdit] = useState<any>(null);
    const [contactoEdit, setContactoEdit] = useState<any>(null);

    const detallesContacto = Array.isArray(cliente.contacto_detalle_cliente)
        ? cliente.contacto_detalle_cliente
        : (cliente as any).contacto_detalle_cliente
            ? [(cliente as any).contacto_detalle_cliente]
            : [];
    const contactos = detallesContacto
        .map((detalle: any) => detalle?.contacto)
        .filter((contacto: any) => !!contacto);

    const requestWithInertia = async (
        method: 'post' | 'put',
        url: string,
        payload: any,
        extraOptions: Record<string, any> = {}
    ): Promise<void> => {
        if (method === 'post' && extraOptions.forceFormData) {
            await axios.post(url, payload, {
                headers: { 'Content-Type': 'multipart/form-data' },
            });
        } else if (method === 'post') {
            await axios.post(url, payload);
        } else if (method === 'put') {
            await axios.put(url, payload);
        }
    };

    return (
        <div className="client-detail-panel fade-in-up h-100">
            {/* Header */}
            <div className="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <h3 className="fw-bold mb-1 text-primary">{cliente.RazSocCli}</h3>
                    <div className="d-flex gap-2">
                        <Badge bg="secondary">{cliente.NumCifCli}</Badge>
                        <Badge bg={cliente.EstCli === 1 ? 'success' : 'danger'}>
                            {cliente.EstCli === 1 ? 'Activo' : 'Inactivo'}
                        </Badge>
                    </div>
                </div>
            </div>

            {/* Row 1: General and Puntos de Suministro */}

            <Row className="g-3 mb-3">

                <Col md={7} lg={8}>

                    <Card className="dashboard-card dashboard-gradient-a h-100">

                        <Card.Header className="d-flex justify-content-between align-items-center border-bottom border-secondary dashboard-header-dark" style={{ paddingBottom: '1rem', paddingTop: '1rem' }}>

                            <div className="d-flex align-items-center gap-2">

                                <Building size={18} className="text-white" />

                                <h6 className="mb-0 fw-bold text-white">Datos del Cliente y Dirección</h6>

                            </div>

                            <Button
                                variant="outline-light"
                                size="sm"
                                className="rounded-pill border-0"
                                onClick={() => setShowEditarModal(true)}
                            >
                                <Edit size={14} className="me-1" /> Editar Datos
                            </Button>

                        </Card.Header>

                        <Card.Body>

                            <div className="client-data-form-view">

                                {/* Razón Social y Nº Documento */}

                                <Row className="mb-2">

                                    <Col md={8}>

                                        <Form.Group>

                                            <Form.Label className="text-muted small fw-bold mb-0">Razón Social / Apellidos, Nombre</Form.Label>

                                            <Form.Control size="sm" type="text" readOnly value={cliente.RazSocCli || ''} className="bg-light" />

                                        </Form.Group>

                                    </Col>

                                    <Col md={4}>

                                        <Form.Group>
                                            <Form.Label className="text-muted small fw-bold mb-0">
                                                Nº Documento <span title="Editar Datos"><Edit size={12} className="ms-1 cursor-pointer text-primary hover-primary" onClick={() => setShowEditarModal(true)} /></span>
                                            </Form.Label>
                                            <Form.Control size="sm" type="text" readOnly value={cliente.NumCifCli || ''} className="bg-light" />

                                        </Form.Group>

                                    </Col>

                                </Row>



                                {/* Dirección, Escalera, Localidad */}

                                <Row className="mb-2">

                                    <Col md={5}>

                                        <Form.Group>

                                            <Form.Label className="text-muted small fw-bold mb-0">Dirección</Form.Label>

                                            <Form.Control size="sm" type="text" readOnly value={`${(cliente as any).NomViaDomFis || ''} ${(cliente as any).NumViaDomFis || ''}`.trim()} className="bg-light" />

                                        </Form.Group>

                                    </Col>

                                    <Col md={3}>

                                        <Form.Group>

                                            <Form.Label className="text-muted small fw-bold mb-0">Escalera / Planta / Puerta</Form.Label>

                                            <Form.Control size="sm" type="text" readOnly value={[(cliente as any).EscDomFis, (cliente as any).PlaDomFis, (cliente as any).PueDomFis].filter(Boolean).join(' / ')} className="bg-light" />

                                        </Form.Group>

                                    </Col>

                                    <Col md={4}>

                                        <Form.Group>

                                            <Form.Label className="text-muted small fw-bold mb-0">Localidad</Form.Label>

                                            <Form.Control size="sm" type="text" readOnly value={(cliente as any).localidad?.DesLoc || ''} className="bg-light" />

                                        </Form.Group>

                                    </Col>

                                </Row>



                                {/* Provincia, Código Postal */}

                                <Row className="mb-2">

                                    <Col md={8}>

                                        <Form.Group>

                                            <Form.Label className="text-muted small fw-bold mb-0">Provincia</Form.Label>

                                            <Form.Control size="sm" type="text" readOnly value={(cliente as any).localidad?.provincia?.DesPro || ''} className="bg-light" />

                                        </Form.Group>

                                    </Col>

                                    <Col md={4}>

                                        <Form.Group>

                                            <Form.Label className="text-muted small fw-bold mb-0">Código Postal</Form.Label>

                                        <Form.Control size="sm" type="text" readOnly value={(cliente as any).localidad.CPLoc || ''} className="bg-light" />

                                        </Form.Group>

                                    </Col>

                                </Row>



                                {/* Teléfonos */}

                                <Row className="mb-2">

                                    <Col md={6}>

                                        <Form.Group>

                                            <Form.Label className="text-muted small fw-bold mb-0">Teléfono Fijo</Form.Label>

                                            <Form.Control size="sm" type="text" readOnly value={cliente.TelFijCli || ''} className="bg-light" />

                                        </Form.Group>

                                    </Col>

                                    <Col md={6}>

                                        <Form.Group>

                                            <Form.Label className="text-muted small fw-bold mb-0">Teléfono Movil</Form.Label>

                                            <Form.Control size="sm" type="text" readOnly value={cliente.TelMovCli || ''} className="bg-light" />

                                        </Form.Group>

                                    </Col>

                                </Row>



                                {/* Emails */}

                                <Row className="mb-2">

                                    <Col md={6}>

                                        <Form.Group>

                                            <Form.Label className="text-muted small fw-bold mb-0">Email</Form.Label>

                                            <Form.Control size="sm" type="text" readOnly value={cliente.EmaCli || ''} className="bg-light" />

                                        </Form.Group>

                                    </Col>

                                    <Col md={6}>

                                        <Form.Group>

                                            <Form.Label className="text-muted small fw-bold mb-0">Email Opcional</Form.Label>

                                            <Form.Control size="sm" type="text" readOnly value={(cliente as any).EmaCliOpc || ''} className="bg-light" />

                                        </Form.Group>

                                    </Col>

                                </Row>



                                {cliente.ObsCli && (

                                    <Row className="mt-2">

                                        <Col md={12}>

                                            <Form.Group>

                                                <Form.Label className="text-muted small fw-bold mb-0">Notas</Form.Label>

                                                <div className="text-muted small bg-light border p-2 rounded">{cliente.ObsCli}</div>

                                            </Form.Group>

                                        </Col>

                                    </Row>

                                )}

                            </div>

                        </Card.Body>

                    </Card>

                </Col>



                {/* Puntos de Suministro */}

                <Col md={5} lg={4}>

                    <Card className="dashboard-card dashboard-gradient-b h-100">

                        <Card.Header className="d-flex justify-content-between align-items-center border-bottom border-secondary dashboard-header-dark" style={{ paddingBottom: '1rem', paddingTop: '1rem' }}>

                             <div className="d-flex align-items-center gap-2">

                                <MapPin size={18} className="text-white" />

                                <h6 className="mb-0 fw-bold text-white">Puntos de Suministro ({ (cliente.puntos_suministro || []).length })</h6>

                            </div>

                            <Button variant="outline-light" size="sm" className="rounded-pill border-0" onClick={() => setShowCrearPuntoModal(true)}>

                                <Plus size={14} className="me-1" /> Nuevo Punto

                            </Button>

                        </Card.Header>

                        <Card.Body className="p-0 overflow-y-auto" style={{ maxHeight: '350px' }}>

                            {(cliente.puntos_suministro || []).length > 0 ? (

                                <div className="list-group list-group-flush">

                                    {(cliente.puntos_suministro || []).map((punto: any, idx: number) => (

                                        <div key={idx} className="list-group-item bg-transparent border-bottom border-secondary-subtle d-flex justify-content-between align-items-center p-3 hover-bg-light transition-all dashboard-soft-list-item">

                                            <div>

                                                <div className="text-dark small mb-2 lh-base">
                                                    <span className="fw-bold">Dirección:</span> {[
                                                        punto.NomViaPunSum,
                                                        punto.NumViaPunSum,
                                                        punto.BloPunSum ? `Bloque ${punto.BloPunSum}` : null,
                                                        punto.EscPunSum ? `Escalera ${punto.EscPunSum}` : null,
                                                        punto.PlaPunSum ? `Planta ${punto.PlaPunSum}` : null,
                                                        punto.PuePunSum ? `Puerta ${punto.PuePunSum}` : null,
                                                        punto.CPLocSoc,
                                                        punto.localidad?.provincia?.DesPro,
                                                        punto.localidad?.DesLoc
                                                    ].filter(Boolean).join(', ')}
                                                </div>
                                                <div className="d-flex flex-column gap-1">
                                                    {(punto.cups_electrico || punto.cupsElectrico || []).map((e: any, idx: number) => (
                                                        <div key={e.CodCupsEle || `ele-${idx}`} className="d-flex align-items-center gap-2 text-muted small border-bottom border-secondary-subtle pb-1">
                                                            <Zap size={14} className="text-warning fill-warning flex-shrink-0" />
                                                            <span className="font-monospace text-dark fw-medium">{e.CUPsEle || e.CupsEle || e.cups}</span>
                                                        </div>
                                                    ))}
                                                    {(punto.cups_gas || punto.cupsGas || []).map((g: any, idx: number) => (
                                                        <div key={g.CodCupGas || g.CodCupsGas || `gas-${idx}`} className="d-flex align-items-center gap-2 text-muted small border-bottom border-secondary-subtle pb-1">
                                                            <Flame size={14} className="text-danger flex-shrink-0" />
                                                            <span className="font-monospace text-dark fw-medium">{g.CupsGas || g.CUPsGas || g.cups}</span>
                                                        </div>
                                                    ))}
                                                    {!((punto.cups_electrico || punto.cupsElectrico || [])?.length) && !((punto.cups_gas || punto.cupsGas || [])?.length) && (
                                                        <div className="text-muted small fst-italic">Sin CUPS asociados</div>
                                                    )}
                                                </div>

                                            </div>

                                            <Button

                                                variant="outline-secondary"

                                                size="sm"

                                                className="btn-icon rounded-circle text-muted hover-primary border-0"

                                                onClick={() => {

                                                    setPuntoEdit(punto);

                                                    setShowEditarPuntoModal(true);

                                                }}

                                            >

                                                <Edit size={16} />

                                            </Button>

                                        </div>

                                    ))}

                                </div>

                            ) : (

                                <div className="d-flex flex-column align-items-center justify-content-center h-100 text-muted p-4">

                                    <MapPin size={32} className="mb-2 opacity-50" />

                                    <p className="small text-center">No hay puntos de suministro registrados.</p>

                                </div>

                            )}

                        </Card.Body>

                    </Card>

                </Col>

            </Row>



            {/* Row 2: Contacto, Bancos, Documentos */}

            <Row className="g-3 mb-3">

                {/* Contacto Principal */}

                <Col md={4}>

                    <Card className="h-100 dashboard-card dashboard-gradient-b">

                        <Card.Header className="d-flex justify-content-between align-items-center border-bottom border-secondary dashboard-header-dark" style={{ paddingBottom: '1rem', paddingTop: '1rem' }}>

                            <div className="d-flex align-items-center gap-2">

                                <Users size={18} className="text-white" />

                                <h6 className="mb-0 fw-bold text-white">Contacto</h6>

                            </div>

                             {contactos.length > 0 ? (

                                <Button size="sm" variant="link" className="p-0 text-decoration-none text-white" onClick={() => {

                                    setContactoEdit(contactos[0]);

                                    setShowEditarContactoModal(true);

                                }}>

                                    <Edit size={14} />

                                </Button>

                            ) : null}

                        </Card.Header>

                        <Card.Body>

                            {contactos.length > 0 ? (

                                <div className="d-flex flex-column gap-2">

                                    {contactos.map((contacto: any) => (

                                        <div key={contacto.CodConCli} className="d-flex justify-content-between align-items-start border-bottom border-secondary-subtle pb-2">

                                            <div>

                                                <div className="fw-bold fs-6 mb-1 text-dark">{contacto.NomConCli}</div>

                                                <div className="text-muted small mb-1">{contacto.CarConCli || 'Sin cargo'}</div>

                                                <div className="text-muted small mb-1">{contacto.EmaConCli || 'Sin email'}</div>

                                                <div className="text-muted small">Fijo: {contacto.TelFijConCli || 'Sin teléfono fijo'}</div>

                                                <div className="text-muted small">Móvil: {contacto.TelCelConCli || 'Sin teléfono móvil'}</div>

                                            </div>

                                            <Button

                                                size="sm"

                                                variant="link"

                                                className="p-0 text-decoration-none"

                                                onClick={() => {

                                                    setContactoEdit(contacto);

                                                    setShowEditarContactoModal(true);

                                                }}

                                            >

                                                <Edit size={14} />

                                            </Button>

                                        </div>

                                    ))}

                                </div>

                            ) : (

                                <div className="text-center py-2">

                                    <span className="text-muted small d-block mb-2">No asignado</span>

                                    <Button size="sm" variant="outline-dark" className="py-0 px-2 rounded-pill" onClick={() => setShowCrearContactoModal(true)}>

                                        <Plus size={12} /> Asignar

                                    </Button>

                                </div>

                            )}

                        </Card.Body>

                    </Card>

                </Col>



                {/* Cuentas Bancarias */}

                <Col md={4}>

                    <Card className="h-100 dashboard-card dashboard-gradient-a">

                        <Card.Header className="d-flex justify-content-between align-items-center border-bottom border-secondary dashboard-header-dark" style={{ paddingBottom: '1rem', paddingTop: '1rem' }}>

                             <div className="d-flex align-items-center gap-2">

                                <CreditCard size={18} className="text-white" />

                                <h6 className="mb-0 fw-bold text-white">Bancos ({ (cliente.cuentas_bancarias_activas || []).length })</h6>

                            </div>

                            <Button variant="outline-light" size="sm" className="rounded-pill border-0" onClick={() => setShowCrearCuentaModal(true)}>

                                <Plus size={14} className="me-1" /> Nuevo Banco

                            </Button>

                        </Card.Header>

                        <Card.Body className="overflow-auto" style={{ maxHeight: '140px' }}>

                             {(cliente.cuentas_bancarias_activas || []).length > 0 ? (

                                <div className="d-flex flex-column gap-2">

                                    {(cliente.cuentas_bancarias_activas || []).map((cue: any, idx: number) => (

                                        <div key={idx} className="d-flex justify-content-between align-items-center border-bottom border-secondary-subtle pb-1">

                                            <div className="text-truncate small text-dark" title={cue.NumIBan}>

                                                <div className="font-monospace">{cue.NumIBan}</div>

                                                <div className="text-muted">{cue?.ObserCuenBan || 'Sin observaciones'}</div>

                                            </div>

                                            <Edit

                                                size={12}

                                                className="text-muted cursor-pointer hover-primary ms-1"

                                                onClick={() => {

                                                    setCuentaEdit(cue);

                                                    setShowEditarCuentaModal(true);

                                                }}

                                            />

                                        </div>

                                    ))}

                                </div>

                             ) : (

                                <div className="text-center text-muted small py-2">Sin cuentas</div>

                             )}

                        </Card.Body>

                    </Card>

                </Col>



                {/* Documentos */}

                <Col md={4}>

                    <Card className="dashboard-card dashboard-gradient-a h-100">

                        <Card.Header className="d-flex justify-content-between align-items-center border-bottom border-secondary dashboard-header-dark" style={{ paddingBottom: '1rem', paddingTop: '1rem' }}>

                             <div className="d-flex align-items-center gap-2">

                                <FileText size={18} className="text-white" />

                                <h6 className="mb-0 fw-bold text-white">Documentos ({ (cliente.documentos_clientes || []).length })</h6>

                            </div>

                            <Button variant="outline-light" size="sm" className="rounded-pill border-0" onClick={() => setShowSubirDocumentoModal(true)}>

                                <Plus size={14} className="me-1" /> Subir

                            </Button>

                        </Card.Header>

                        <Card.Body className="p-3 overflow-y-auto bg-transparent" style={{ maxHeight: '350px' }}>

                             {(cliente.documentos_clientes || []).length > 0 ? (

                                <div className="d-flex flex-column gap-2">

                                    {(cliente.documentos_clientes || []).map((doc: any) => (

                                        <div key={doc.id} className="w-100">

                                            <DocumentoCard 
                                                doc={doc} 
                                                onDelete={async (uuid) => {
                                                    const result = await Swal.fire({
                                                        title: '¿Eliminar documento?',
                                                        text: 'Esta acción no se puede deshacer',
                                                        icon: 'warning',
                                                        showCancelButton: true,
                                                        confirmButtonColor: '#dc3545',
                                                        cancelButtonColor: '#6c757d',
                                                        confirmButtonText: 'Sí, eliminar',
                                                        cancelButtonText: 'Cancelar'
                                                    });
                                                    if (result.isConfirmed) {
                                                        loading.show();
                                                        try {
                                                            await axios.delete(route('clientes.documento.destroy', uuid));
                                                            await refreshData();
                                                            Swal.fire({ title: 'Éxito', text: 'Documento eliminado correctamente', icon: 'success', timer: 1500, showConfirmButton: false });
                                                        } catch(e: any) {
                                                            Swal.fire({ title: 'Error', text: e?.response?.data?.message || 'Error al eliminar el documento', icon: 'error' });
                                                        } finally {
                                                            loading.hide();
                                                        }
                                                    }
                                                }}
                                            />

                                        </div>

                                    ))}

                                </div>

                            ) : (

                                <div className="d-flex flex-column align-items-center justify-content-center h-100 text-muted p-4">

                                    <FileText size={32} className="mb-2 opacity-50" />

                                    <p className="small text-center">No hay documentos asociados.</p>

                                </div>

                            )}

                        </Card.Body>

                    </Card>

                </Col>

            </Row>

            {/* Modals */}
            {showEditarModal && (
                <EditarClienteModal
                    show={showEditarModal}
                    onHide={() => setShowEditarModal(false)}
                    cliente={cliente}
                    onUpdated={async () => {
                        await refreshData();
                    }}
                />
            )}

            {showEditarContactoModal && contactoEdit && (
                <EditarContactoModal
                    show={showEditarContactoModal}
                    onHide={() => setShowEditarContactoModal(false)}
                    contacto={contactoEdit}
                    onUpdated={async (updated) => {
                        loading.show();
                        try {
                            await requestWithInertia('put', route('clientes.contacto.update', updated.CodConCli), updated);
                            await refreshData();
                            setShowEditarContactoModal(false);
                            Swal.fire({ title: 'Éxito', text: 'Contacto actualizado correctamente.', icon: 'success', timer: 1800, showConfirmButton: false });
                        } catch (e: any) {
                            Swal.fire({ title: 'Error', text: e?.response?.data?.message, icon: 'error' });
                        } finally {
                            loading.hide();
                        }
                    }}
                />
            )}

            {showEditarCuentaModal && cuentaEdit && (
                <EditarCuentaBancariaModal
                    show={showEditarCuentaModal}
                    onHide={() => setShowEditarCuentaModal(false)}
                    cuenta={cuentaEdit}
                    onUpdated={async (updated) => {
                        loading.show();
                        try {
                            const payload = {
                                NumIBan: updated.NumIBan,
                                ObserCuenBan: updated.ObserCuenBan,
                            };
                            await requestWithInertia('put', route('clientes.cuenta-bancaria.update', updated.CodCueBan), payload);
                            await refreshData();
                            setShowEditarCuentaModal(false);
                            Swal.fire({ title: 'Éxito', text: 'Cuenta bancaria actualizada correctamente.', icon: 'success', timer: 1800, showConfirmButton: false });
                        } catch (e: any) {
                            Swal.fire({ title: 'Error', text: e?.response?.data?.message , icon: 'error' });
                        } finally {
                            loading.hide();
                        }
                    }}
                />
            )}

            {showEditarPuntoModal && puntoEdit && (
                <EditarPuntoSuministroModal
                    show={showEditarPuntoModal}
                    onHide={() => setShowEditarPuntoModal(false)}
                    punto={puntoEdit}
                    onUpdated={async (updated) => {
                        loading.show();
                        try {
                            await refreshData();
                            setShowEditarPuntoModal(false);
                        } finally {
                            loading.hide();
                        }
                    }}
                />
            )}

            {showCrearContactoModal && (
                <CrearContactoModal
                    show={showCrearContactoModal}
                    onHide={() => setShowCrearContactoModal(false)}
                    codCli={cliente.CodCli}
                    onCreate={async (payload) => {
                        loading.show();
                        try {
                            await requestWithInertia('post', route('clientes.contacto.store'), payload);
                            await refreshData();
                            setShowCrearContactoModal(false);
                            Swal.fire({ title: 'Éxito', text: 'Contacto creado correctamente.', icon: 'success', timer: 1800, showConfirmButton: false });
                        } catch (e: any) {
                            Swal.fire({ title: 'Error', text: e?.response?.data?.message || 'Error al crear', icon: 'error' });
                        } finally {
                            loading.hide();
                        }
                    }}
                />
            )}

            {showCrearCuentaModal && (
                <CrearCuentaBancariaModal
                    show={showCrearCuentaModal}
                    onHide={() => setShowCrearCuentaModal(false)}
                    codCli={cliente.CodCli}
                    onCreate={async (payload) => {
                        loading.show();
                        try {
                            await requestWithInertia('post', route('clientes.cuenta-bancaria.store'), payload);
                            await refreshData();
                            setShowCrearCuentaModal(false);
                            Swal.fire({ title: 'Éxito', text: 'Cuenta bancaria creada correctamente.', icon: 'success', timer: 1800, showConfirmButton: false });
                        } catch (e: any) {
                            Swal.fire({ title: 'Error', text: e?.response?.data?.message || 'Error al crear', icon: 'error' });
                        } finally {
                            loading.hide();
                        }
                    }}
                />
            )}

            {showCrearPuntoModal && (
                <CrearPuntoSuministroModal
                    show={showCrearPuntoModal}
                    onHide={() => setShowCrearPuntoModal(false)}
                    codCli={cliente.CodCli}
                    onCreate={async (payload) => {
                        loading.show();
                        try {
                            await requestWithInertia('post', route('puntos-suministro.store'), payload);
                            await refreshData();
                            setShowCrearPuntoModal(false);
                            Swal.fire({ title: 'Éxito', text: 'Punto de suministro creado correctamente.', icon: 'success', timer: 1800, showConfirmButton: false });
                        } catch (e: any) {
                            Swal.fire({ title: 'Error', text: e?.response?.data?.message || 'Error al crear', icon: 'error' });
                        } finally {
                            loading.hide();
                        }
                    }}
                />
            )}

            {showSubirDocumentoModal && (
                <SubirDocumentoModal
                    show={showSubirDocumentoModal}
                    onHide={() => setShowSubirDocumentoModal(false)}
                    codCli={cliente.CodCli}
                    onUpload={async (formData) => {
                        loading.show();
                        try {
                            await axios.post(route('clientes.documento.store'), formData, {
                                headers: { 'Content-Type': 'multipart/form-data' },
                            });
                            await refreshData();
                            setShowSubirDocumentoModal(false);
                            Swal.fire({ title: 'Éxito', text: 'Documento subido correctamente', icon: 'success', timer: 1800, showConfirmButton: false });
                        } catch (e: any) {
                            Swal.fire({ title: 'Error', text: e?.response?.data?.message || 'Error al subir documento', icon: 'error' });
                        } finally {
                            loading.hide();
                        }
                    }}
                />
            )}
        </div>
    );
};

export default ClientDetailPanel;
