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 Comercializadora {
    CodCom: number;
    RazSocCom: string;
    NumCifCom: string;
}

interface Producto {
    CodPro: number;
    DesPro: string;
    CodCom: number;
    SerGas: number;
    SerEle: number;
    EstPro: number;
    FecIniPro: string;
    CodigoServicio: string;
    ObsPro: string;
    comercializadora?: Comercializadora;
    created_at: string;
    updated_at: string;
}

const ConsultaProducto = ({ producto }: { producto: Producto }) => {
    const { showLoading, hideLoading } = useLoading();
    console.log('Producto recibido en ConsultaProducto:', producto);
    const handleEdit = () => {
        showLoading();
        router.visit(route('productos.editar', producto.CodPro), {
            onFinish: () => hideLoading()
        });
    };

    const handleBack = () => {
        showLoading();
        router.visit(route('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={`Producto: ${producto.DesPro}`} />
            <div className="page-content">
                <Container fluid>
                    <BreadCrumb title="Consulta" pageTitle="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">
                                        Producto: {producto.DesPro}
                                        <Badge
                                            bg={producto.EstPro === 1 ? "success" : "danger"}
                                            className="ms-2"
                                        >
                                            {producto.EstPro === 1 ? "Activo" : "Suspendido"}
                                        </Badge>
                                    </h4>
                                    <Button
                                        variant="primary"
                                        onClick={handleEdit}
                                        className="d-flex align-items-center"
                                    >
                                        <Edit size={16} className="me-1" />
                                        Editar Producto
                                    </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 Producto:</label>
                                                <p className="mb-2">{producto.CodPro}</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">{producto.DesPro}</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">{producto.CodigoServicio || 'No especificado'}</p>
                                            </div>
                                        </Col>

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">Estado:</label>
                                                <p className="mb-2">
                                                    <Badge bg={producto.EstPro === 1 ? "success" : "danger"}>
                                                        {producto.EstPro === 1 ? "Activo" : "Suspendido"}
                                                    </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(producto.FecIniPro)}</p>
                                            </div>
                                        </Col>

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

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

                                        <Col md={6} lg={4}>
                                            <div className="info-item">
                                                <label className="fw-bold text-muted">NIF/CIF:</label>
                                                <p className="mb-2">
                                                    {producto.comercializadora?.NumCifCom || 'No disponible'}
                                                </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 Ofrecidos
                                            </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={producto.SerGas ? "success" : "secondary"}>
                                                        {producto.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={producto.SerEle ? "success" : "secondary"}>
                                                        {producto.SerEle ? "Sí" : "No"}
                                                    </Badge>
                                                </p>
                                            </div>
                                        </Col>

                                        {/* Observaciones */}
                                        {producto.ObsPro && (
                                            <>
                                                <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">
                                                            {producto.ObsPro}
                                                        </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(producto.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(producto.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 Productos
                                    </Button>
                                    <Button
                                        variant="primary"
                                        onClick={handleEdit}
                                    >
                                        <Edit size={16} className="me-1" />
                                        Editar Producto
                                    </Button>
                                </Card.Footer>
                            </Card>
                        </Col>
                    </Row>
                </Container>
            </div>
        </React.Fragment>
    );
};

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