import React from "react";
import {
    Card,
    Col,
    Container,
    Row,
    Button,
    Badge
} from "react-bootstrap";
import { Head, router } from "@inertiajs/react";
import { Edit, FileText } from "lucide-react";
import BreadCrumb from "../../../../Components/Common/BreadCrumb";
import Layout from "../../../../Layouts";
import { useLoading } from '../../../../LoadingContext';
import { formatCalendarDateEs } from '../../../../utils/serverCalendarDate';

interface Producto {
    CodPro: number;
    DesPro: string;
    CodigoServicio: string;
    comercializadora?: {
        CodCom: number;
        RazSocCom: string;
        NumCifCom: string;
    };
}

interface TipoComision {
    CodTipCom: number;
    DesTipCom: string;
}

interface AnexoProducto {
    CodAnePro: number;
    DesAnePro: string;
    CodPro: number;
    SerGas: number;
    SerEle: number;
    TipPre: string;
    DocAnePro: string;
    FecCreateDoc: string;
    ObsAnePro: string;
    FecIniAne: string;
    CodTipCom: number;
    EstCom: number;
    EstAne: number;
    producto?: Producto;
    tipoComision?: TipoComision;
    created_at: string;
    updated_at: string;
}

const ConsultaAnexoProducto = ({ anexoProducto }: { anexoProducto: AnexoProducto }) => {
    const { showLoading, hideLoading } = useLoading();

    const handleEdit = () => {
        showLoading();
        router.visit(route('anexo-productos.edit', anexoProducto.CodAnePro), {
            onFinish: () => hideLoading()
        });
    };

    const handleBack = () => {
        showLoading();
        router.visit(route('anexo-productos.index'), {
            onFinish: () => hideLoading()
        });
    };

    const formatDate = (dateString: string) => {
        if (!dateString) return 'No especificada';
        const s = formatCalendarDateEs(dateString);
        return s === '-' ? 'No especificada' : s;
    };

    const formatDateTime = (dateString: string) => {
        if (!dateString) return 'No especificada';
        return new Date(dateString).toLocaleString('es-ES', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    return (
        <React.Fragment>
            <Head title={`Anexo: ${anexoProducto.DesAnePro}`} />
            <div className="page-content">
                <Container fluid>
                    <BreadCrumb title="Consulta" pageTitle="Anexo de Producto" />
                    <Row>
                        <Col xl={12}>
                            <Card>
                                <Card.Header className="d-flex justify-content-between align-items-center bg-light">
                                    <h4 className="card-title mb-0">
                                        Anexo: {anexoProducto.DesAnePro}
                                        <Badge
                                            bg={anexoProducto.EstAne === 1 ? "success" : "danger"}
                                            className="ms-2"
                                        >
                                            {anexoProducto.EstAne === 1 ? "Activo" : "Suspendido"}
                                        </Badge>
                                    </h4>
                                    <Button
                                        variant="primary"
                                        onClick={handleEdit}
                                        className="d-flex align-items-center"
                                    >
                                        <Edit size={16} className="me-1" />
                                        Editar Anexo
                                    </Button>
                                </Card.Header>
                                <Card.Body>
                                    <Row className="g-4">
                                        {/* Información General */}
                                        <Col xs={12}>
                                            <h5 className="text-primary border-bottom pb-2 mb-3">
                                                <i className="fas fa-info-circle me-2"></i>
                                                Información General
                                            </h5>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">ID del Anexo:</label>
                                                <p className="mb-2">{anexoProducto.CodAnePro}</p>
                                            </div>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Descripción:</label>
                                                <p className="mb-2">{anexoProducto.DesAnePro}</p>
                                            </div>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Tipo de Precio:</label>
                                                <p className="mb-2">{anexoProducto.TipPre || 'No especificado'}</p>
                                            </div>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Estado del Anexo:</label>
                                                <p className="mb-2">
                                                    <Badge bg={anexoProducto.EstAne === 1 ? "success" : "danger"}>
                                                        {anexoProducto.EstAne === 1 ? "Activo" : "Suspendido"}
                                                    </Badge>
                                                </p>
                                            </div>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Estado Comercial:</label>
                                                <p className="mb-2">
                                                    <Badge bg={anexoProducto.EstCom === 1 ? "success" : "secondary"}>
                                                        {anexoProducto.EstCom === 1 ? "Comercial" : "No Comercial"}
                                                    </Badge>
                                                </p>
                                            </div>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Fecha de Inicio:</label>
                                                <p className="mb-2">{formatDate(anexoProducto.FecIniAne)}</p>
                                            </div>
                                        </Col>

                                        {/* Producto Asociado */}
                                        <Col xs={12}>
                                            <hr className="my-3" />
                                            <h5 className="text-primary border-bottom pb-2 mb-3">
                                                <i className="fas fa-box me-2"></i>
                                                Producto Asociado
                                            </h5>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Nombre del Producto:</label>
                                                <p className="mb-2">
                                                    {anexoProducto.producto?.DesPro || 'No asignado'}
                                                </p>
                                            </div>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Código de Servicio:</label>
                                                <p className="mb-2">
                                                    {anexoProducto.producto?.CodigoServicio || 'No disponible'}
                                                </p>
                                            </div>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Comercializadora:</label>
                                                <p className="mb-2">
                                                    {anexoProducto.producto?.comercializadora?.RazSocCom || 'No disponible'}
                                                </p>
                                            </div>
                                        </Col>

                                        {/* Tipo de Comisión */}
                                        {anexoProducto.tipoComision && (
                                            <>
                                                <Col xs={12}>
                                                    <hr className="my-3" />
                                                    <h5 className="text-primary border-bottom pb-2 mb-3">
                                                        <i className="fas fa-percentage me-2"></i>
                                                        Tipo de Comisión
                                                    </h5>
                                                </Col>
                                                <Col md={6}>
                                                    <div className="info-item">
                                                        <label className="fw-bold text-muted">Descripción:</label>
                                                        <p className="mb-2">{anexoProducto.tipoComision.DesTipCom}</p>
                                                    </div>
                                                </Col>
                                            </>
                                        )}

                                        {/* Servicios */}
                                        <Col xs={12}>
                                            <hr className="my-3" />
                                            <h5 className="text-primary border-bottom pb-2 mb-3">
                                                <i className="fas fa-cogs me-2"></i>
                                                Servicios del Anexo
                                            </h5>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Servicio de Gas:</label>
                                                <p className="mb-2">
                                                    <Badge bg={anexoProducto.SerGas ? "success" : "secondary"}>
                                                        {anexoProducto.SerGas ? "Sí" : "No"}
                                                    </Badge>
                                                </p>
                                            </div>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Servicio Eléctrico:</label>
                                                <p className="mb-2">
                                                    <Badge bg={anexoProducto.SerEle ? "success" : "secondary"}>
                                                        {anexoProducto.SerEle ? "Sí" : "No"}
                                                    </Badge>
                                                </p>
                                            </div>
                                        </Col>

                                        {/* Documentación */}
                                        {(anexoProducto.DocAnePro || anexoProducto.FecCreateDoc) && (
                                            <>
                                                <Col xs={12}>
                                                    <hr className="my-3" />
                                                    <h5 className="text-primary border-bottom pb-2 mb-3">
                                                        <i className="fas fa-file-alt me-2"></i>
                                                        Documentación
                                                    </h5>
                                                </Col>
                                                {anexoProducto.DocAnePro && (
                                                    <Col md={6}>
                                                        <div className="info-item">
                                                            <label className="fw-bold text-muted">Documento:</label>
                                                            <p className="mb-2 bg-light p-3 rounded">
                                                                {anexoProducto.DocAnePro}
                                                            </p>
                                                        </div>
                                                    </Col>
                                                )}
                                                {anexoProducto.FecCreateDoc && (
                                                    <Col md={6}>
                                                        <div className="info-item">
                                                            <label className="fw-bold text-muted">Fecha Creación Documento:</label>
                                                            <p className="mb-2">{formatDate(anexoProducto.FecCreateDoc)}</p>
                                                        </div>
                                                    </Col>
                                                )}
                                            </>
                                        )}

                                        {/* Observaciones */}
                                        {anexoProducto.ObsAnePro && (
                                            <>
                                                <Col xs={12}>
                                                    <hr className="my-3" />
                                                    <h5 className="text-primary border-bottom pb-2 mb-3">
                                                        <i className="fas fa-comment-alt me-2"></i>
                                                        Observaciones
                                                    </h5>
                                                </Col>
                                                <Col xs={12}>
                                                    <div className="info-item">
                                                        <p className="mb-2 bg-light p-3 rounded">
                                                            {anexoProducto.ObsAnePro}
                                                        </p>
                                                    </div>
                                                </Col>
                                            </>
                                        )}

                                        {/* Información del Sistema */}
                                        <Col xs={12}>
                                            <hr className="my-3" />
                                            <h5 className="text-primary border-bottom pb-2 mb-3">
                                                <i className="fas fa-clock me-2"></i>
                                                Información del Sistema
                                            </h5>
                                        </Col>

                                        <Col md={6}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Fecha de Creación:</label>
                                                <p className="mb-2">{formatDateTime(anexoProducto.created_at)}</p>
                                            </div>
                                        </Col>

                                        <Col md={6}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Última Actualización:</label>
                                                <p className="mb-2">{formatDateTime(anexoProducto.updated_at)}</p>
                                            </div>
                                        </Col>
                                    </Row>
                                </Card.Body>
                                <Card.Footer className="text-center">
                                    <Button
                                        variant="secondary"
                                        onClick={handleBack}
                                        className="me-2"
                                    >
                                        <FileText size={16} className="me-1" />
                                        Volver a Anexos
                                    </Button>
                                    <Button
                                        variant="primary"
                                        onClick={handleEdit}
                                    >
                                        <Edit size={16} className="me-1" />
                                        Editar Anexo
                                    </Button>
                                </Card.Footer>
                            </Card>
                        </Col>
                    </Row>
                </Container>
            </div>
        </React.Fragment>
    );
};

ConsultaAnexoProducto.layout = (page: any) => <Layout children={page} />;
export default ConsultaAnexoProducto;
