import React, { useEffect, useState } from "react";
import {
    Card,
    Col,
    Container,
    Row,
    Form,
    Button
} from "react-bootstrap";
import { Head, router, useForm } from "@inertiajs/react";
import { FileText } from "lucide-react";
import BreadCrumb from "../../../../Components/Common/BreadCrumb";
import FormDateInputEs from "../../../../Components/Common/FormDateInputEs";
import Layout from "../../../../Layouts";
import { useLoading } from '../../../../LoadingContext';
import Swal from 'sweetalert2';
import estilosFoco from '../../Contratos/Shared/estilosFocoAccesible.module.css';
import {
  validarCamposObligatoriosMaestro,
  mostrarModalValidacionYEnfocar,
  normalizarErroresServidor,
  ANEXO_CAMPOS_ORDEN,
  ANEXO_ETIQUETAS,
  ANEXO_IDS_DOM,
} from '../Shared/validacionFormularioMaestro';

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: number;
    DocAnePro: string;
    FecCreateDoc: string;
    ObsAnePro: string;
    FecIniAne: string;
    CodTipCom: number;
    EstCom: number;
    EstAne: number;
}

interface EditarAnexoProductoProps {
    anexoProducto?: AnexoProducto;
    productos: Producto[];
    tiposComision: TipoComision[];
    isEdit?: boolean;
}

const EditarAnexoProducto = ({
    anexoProducto,
    productos,
    tiposComision,
    isEdit = false
}: EditarAnexoProductoProps) => {
    const { showLoading, hideLoading } = useLoading();
    const [errors, setErrors] = useState<Record<string, string>>({});

    const manejarErroresValidacion = async (erroresValidacion: Record<string, string>) => {
        setErrors(erroresValidacion);
        await mostrarModalValidacionYEnfocar({
            errores: erroresValidacion,
            camposOrdenados: ANEXO_CAMPOS_ORDEN,
            mapaIdsDom: ANEXO_IDS_DOM,
            tituloModal: 'Faltan campos obligatorios',
        });
    };

    const { data, setData, post, put, processing, reset } = useForm({
        CodAnePro: anexoProducto?.CodAnePro || '',
        DesAnePro: anexoProducto?.DesAnePro || '',
        CodPro: anexoProducto?.CodPro || '',
        SerGas: anexoProducto?.SerGas || 0,
        SerEle: anexoProducto?.SerEle || 0,
        TipPre: anexoProducto?.TipPre || 1,
        DocAnePro: anexoProducto?.DocAnePro || '',
        FecCreateDoc: anexoProducto?.FecCreateDoc || '',
        ObsAnePro: anexoProducto?.ObsAnePro || '',
        FecIniAne: anexoProducto?.FecIniAne || '',
        CodTipCom: anexoProducto?.CodTipCom || '',
        EstCom: anexoProducto?.EstCom || 1,
        EstAne: anexoProducto?.EstAne || 1,
    });

    const clearLocalError = (field: string) => {
        setErrors((prev) => {
            if (!prev[field]) return prev;
            const next = { ...prev };
            delete next[field];
            return next;
        });
    };

    const handleTextChange = (field: string) => (
        e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
    ) => {
        setData(field as any, e.target.value);
        clearLocalError(field);
    };

    const handleSelectChange = (field: string, parser?: (value: string) => any) => (
        e: React.ChangeEvent<HTMLSelectElement>
    ) => {
        const value = parser ? parser(e.target.value) : e.target.value;
        setData(field as any, value);
        clearLocalError(field);
    };

    useEffect(() => {
        if (processing) {
            showLoading();
        } else {
            hideLoading();
        }
    }, [processing]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        const erroresCliente = validarCamposObligatoriosMaestro(
            data,
            ANEXO_CAMPOS_ORDEN,
            ANEXO_ETIQUETAS,
        );
        if (Object.keys(erroresCliente).length > 0) {
            await manejarErroresValidacion(erroresCliente);
            return;
        }

        const submitData = {
            ...data,
            SerGas: Number(data.SerGas),
            SerEle: Number(data.SerEle),
            EstCom: Number(data.EstCom),
            EstAne: Number(data.EstAne),
            CodPro: Number(data.CodPro),
            CodTipCom: Number(data.CodTipCom),
        };

        if (isEdit && anexoProducto) {
            put(route('anexo-productos.update', anexoProducto.CodAnePro), {
                data: submitData,
                onSuccess: () => {
                    Swal.fire({
                        title: '¡Éxito!',
                        text: 'Anexo de producto actualizado correctamente',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        router.visit(route('anexo-productos.index'));
                    });
                },
                onError: (serverErrors) => {
                    void manejarErroresValidacion(normalizarErroresServidor(serverErrors));
                }
            });
        } else {
            post(route('anexo-productos.store'), {
                data: submitData,
                onSuccess: () => {
                    Swal.fire({
                        title: '¡Éxito!',
                        text: 'Anexo de producto creado correctamente',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        router.visit(route('anexo-productos.index'));
                    });
                },
                onError: (serverErrors) => {
                    void manejarErroresValidacion(normalizarErroresServidor(serverErrors));
                }
            });
        }
    };

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

    return (
        <React.Fragment>
            <Head title={isEdit ? `Editar Anexo: ${anexoProducto?.DesAnePro}` : 'Crear Anexo de Producto'} />
            <div className="page-content">
                <Container fluid>
                    <BreadCrumb
                        title={isEdit ? "Editar" : "Crear"}
                        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">
                                        {isEdit
                                            ? `Editar Anexo: ${anexoProducto?.DesAnePro}`
                                            : 'Crear Nuevo Anexo de Producto'
                                        }
                                    </h4>
                                    <div className="d-flex gap-2">
                                        <Button
                                            variant="success"
                                            size="sm"
                                            onClick={handleSubmit}
                                            disabled={processing}
                                        >
                                            <i className="fas fa-save me-2"></i>
                                            {isEdit ? 'Guardar' : 'Crear'}
                                        </Button>
                                        <Button
                                            variant="secondary"
                                            size="sm"
                                            onClick={handleCancel}
                                        >
                                            <FileText size={14} className="me-1" />
                                            Volver
                                        </Button>
                                    </div>
                                </Card.Header>
                                <Card.Body>
                                    <div className={`${estilosFoco.contenedorAccesibleContratos} formularioAnexoProducto`}>
                                    <Form onSubmit={handleSubmit}>
                                        <Row className="g-3">
                                            {/* Información Básica */}
                                            <Col xs={12}>
                                                <h5 className="text-primary border-bottom pb-2 mb-3">
                                                    Información Básica
                                                </h5>
                                            </Col>

                                            <Col md={6}>
                                                <Form.Group controlId="DesAnePro">
                                                    <Form.Label className="required">
                                                        Descripción del Anexo
                                                    </Form.Label>
                                                    <Form.Control
                                                        type="text"
                                                        value={data.DesAnePro}
                                                        onChange={handleTextChange('DesAnePro')}
                                                        placeholder="Ingrese la descripción del anexo"
                                                        isInvalid={!!errors.DesAnePro}
                                                    />
                                                    {errors.DesAnePro && (
                                                        <Form.Control.Feedback type="invalid">
                                                            {errors.DesAnePro}
                                                        </Form.Control.Feedback>
                                                    )}
                                                </Form.Group>
                                            </Col>

                                            <Col md={6}>
                                                <Form.Group controlId="CodPro">
                                                    <Form.Label className="required">
                                                        Producto
                                                    </Form.Label>
                                                    <Form.Select
                                                        value={data.CodPro}
                                                        onChange={handleSelectChange('CodPro')}
                                                        isInvalid={!!errors.CodPro}
                                                    >
                                                        <option value="">Seleccione un producto</option>
                                                        {productos.map((producto) => (
                                                            <option key={producto.CodPro} value={producto.CodPro}>
                                                                {producto.DesPro}
                                                                {producto.comercializadora && (
                                                                    ` - ${producto.comercializadora.RazSocCom}`
                                                                )}
                                                            </option>
                                                        ))}
                                                    </Form.Select>
                                                    {errors.CodPro && (
                                                        <Form.Control.Feedback type="invalid">
                                                            {errors.CodPro}
                                                        </Form.Control.Feedback>
                                                    )}
                                                </Form.Group>
                                            </Col>

                                            {/*
                                            <Col md={6}>
                                                <Form.Group>
                                                    <Form.Label className="required">
                                                        Tipo de Comisión
                                                    </Form.Label>
                                                    <Form.Select
                                                        value={data.CodTipCom}
                                                        onChange={handleSelectChange('CodTipCom')}
                                                        isInvalid={!!errors.CodTipCom}
                                                    >
                                                        <option value="">Seleccione un tipo de comisión</option>
                                                        {tiposComision.map((tipo) => (
                                                            <option key={tipo.CodTipCom} value={tipo.CodTipCom}>
                                                                {tipo.DesTipCom}
                                                            </option>
                                                        ))}
                                                    </Form.Select>
                                                    {errors.CodTipCom && (
                                                        <Form.Control.Feedback type="invalid">
                                                            {errors.CodTipCom}
                                                        </Form.Control.Feedback>
                                                    )}
                                                </Form.Group>
                                            </Col>
                                            */}
                                            <Col md={6}>
                                                <Form.Group controlId="FecIniAne">
                                                    <Form.Label className="required">
                                                        Fecha de Inicio
                                                    </Form.Label>
                                                    <FormDateInputEs
                                                        id="FecIniAne"
                                                        value={data.FecIniAne || ''}
                                                        onChange={(iso) => {
                                                            setData('FecIniAne' as any, iso);
                                                            clearLocalError('FecIniAne');
                                                        }}
                                                        isInvalid={!!errors.FecIniAne}
                                                    />
                                                    {errors.FecIniAne && (
                                                        <Form.Control.Feedback type="invalid">
                                                            {errors.FecIniAne}
                                                        </Form.Control.Feedback>
                                                    )}
                                                </Form.Group>
                                            </Col>

                                            <Col md={6}>
                                                <Form.Group controlId="TipPre">
                                                    <Form.Label>
                                                        Tipo de Precio
                                                    </Form.Label>
                                                    <Form.Select
                                                        value={data.TipPre}
                                                        onChange={handleSelectChange('TipPre', (value) => Number(value))}
                                                        isInvalid={!!errors.TipPre}
                                                    >
                                                        <option value={1}>Fijo</option>
                                                        <option value={2}>Indexado</option>
                                                    </Form.Select>
                                                    {errors.TipPre && (
                                                        <Form.Control.Feedback type="invalid">
                                                            {errors.TipPre}
                                                        </Form.Control.Feedback>
                                                    )}
                                                </Form.Group>
                                            </Col>

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

                                            <Col md={6}>
                                                <Form.Group>
                                                    <Form.Check
                                                        type="checkbox"
                                                        id="SerGas"
                                                        label="Servicio de Gas"
                                                        checked={data.SerGas === 1}
                                                        onChange={(e) => {
                                                            setData('SerGas', e.target.checked ? 1 : 0);
                                                            clearLocalError('SerGas');
                                                        }}
                                                    />
                                                </Form.Group>
                                            </Col>

                                            <Col md={6}>
                                                <Form.Group>
                                                    <Form.Check
                                                        type="checkbox"
                                                        id="SerEle"
                                                        label="Servicio Eléctrico"
                                                        checked={data.SerEle === 1}
                                                        onChange={(e) => {
                                                            setData('SerEle', e.target.checked ? 1 : 0);
                                                            clearLocalError('SerEle');
                                                        }}
                                                    />
                                                </Form.Group>
                                            </Col>

                                            {/* Estados */}
                                            <Col xs={12}>
                                                <hr className="my-3" />
                                                <h5 className="text-primary border-bottom pb-2 mb-3">
                                                    Estados del Anexo
                                                </h5>
                                            </Col>

                                            <Col md={6}>
                                                <Form.Group>
                                                    <Form.Label>Estado del Anexo</Form.Label>
                                                    <Form.Select
                                                        value={data.EstAne}
                                                        onChange={handleSelectChange('EstAne', (value) => Number(value))}
                                                    >
                                                        <option value={1}>Activo</option>
                                                        <option value={0}>Suspendido</option>
                                                    </Form.Select>
                                                </Form.Group>
                                            </Col>

                                            <Col md={6}>
                                                <Form.Group>
                                                    <Form.Label>Estado Comercial</Form.Label>
                                                    <Form.Select
                                                        value={data.EstCom}
                                                        onChange={handleSelectChange('EstCom', (value) => Number(value))}
                                                    >
                                                        <option value={1}>Comercial</option>
                                                        <option value={0}>No Comercial</option>
                                                    </Form.Select>
                                                </Form.Group>
                                            </Col>

                                            {/* Documentación */}
                                            <Col xs={12}>
                                                <hr className="my-3" />
                                                <h5 className="text-primary border-bottom pb-2 mb-3">
                                                    Documentación
                                                </h5>
                                            </Col>

                                            <Col md={6}>
                                                <Form.Group>
                                                    <Form.Label>
                                                        Documento del Anexo
                                                    </Form.Label>
                                                    <Form.Control
                                                        as="textarea"
                                                        rows={3}
                                                        value={data.DocAnePro}
                                                        onChange={handleTextChange('DocAnePro')}
                                                        placeholder="Ingrese información del documento"
                                                    />
                                                </Form.Group>
                                            </Col>

                                            {/*
                                            <Col md={6}>
                                                <Form.Group>
                                                    <Form.Label>
                                                        Fecha de Creación del Documento
                                                    </Form.Label>
                                                    <Form.Control
                                                        type="date"
                                                        value={data.FecCreateDoc}
                                                        onChange={handleTextChange('FecCreateDoc')}
                                                    />
                                                </Form.Group>
                                            </Col>
                                            */}

                                            <Col xs={12}>
                                                <Form.Group>
                                                    <Form.Label>
                                                        Observaciones
                                                    </Form.Label>
                                                    <Form.Control
                                                        as="textarea"
                                                        rows={4}
                                                        value={data.ObsAnePro}
                                                        onChange={handleTextChange('ObsAnePro')}
                                                        placeholder="Ingrese observaciones adicionales"
                                                    />
                                                </Form.Group>
                                            </Col>
                                        </Row>
                                    </Form>
                                    </div>
                                </Card.Body>
                            </Card>
                        </Col>
                    </Row>
                </Container>
            </div>
        </React.Fragment>
    );
};

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