import {
    CardContainer,
    CheckBoxApp,
    EnterpriseGuard,
    IconApp,
    InputApp,
    InputGoogleMapsSearchAddress,
    LoadingApp,
    SelectSearchApp,
} from "@components";
import {
    AVACLICK_COMMON_AMENITIES_OPTIONS,
    AVACLICK_CONSERVATION_OPTIONS,
    AVACLICK_PRIVATE_AMENITIES_OPTIONS,
    AVACLICK_PROPERTY_TYPES_OPTIONS,
} from "@components/Options/OptionsAvaclick";
import { hasEnterpriseModule } from "@helpers/enterpriseOperationRules";
import { useEnterpriseSelection } from "@hooks/useEnterpriseSelection";
import { useForm } from "@hooks/useForm";
import React, { useEffect, useState } from "react";
import { Accordion, Button, Col, Row } from "react-bootstrap";
import { useDispatch } from "react-redux";
import { useNavigate, useParams } from "react-router-dom";
import Swal from "sweetalert2";
import {
    startCreate,
    startUpdate,
    startLoadProperty,
} from "@redux/slices/users/RealEstateProperties";
import {
    StatusBadge,
    TechnicalMessageList,
    TechnicalResponseAccordionItem,
    ProminentReportLink,
} from "./RealEstatePropertyTechnicalResults";
import {
    defaultValues,
    extractAddressData,
    formatDateTime,
    getFormValues,
    getPropertyReportLinks,
    getPropertyTechnicalErrors,
    getValidationErrors,
} from "@helpers/RealEstatePropertyHelpers";

const SectionCard = ({
    title = "",
    subtitle = "",
    children = null,
    className = "",
}) => {
    return (
        <div className={`card border-0 shadow-sm ${className}`}>
            <div className="card-body p-4">
                <div className="mb-3">
                    <h5 className="mb-1">{title}</h5>
                    {subtitle ? (
                        <p className="text-muted mb-0">{subtitle}</p>
                    ) : null}
                </div>
                {children}
            </div>
        </div>
    );
};

export default function RealEstatePropertyFormScreen() {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const { property_id } = useParams();
    const { activeEnterprise } = useEnterpriseSelection();
    const canAccessRealEstateProperties = hasEnterpriseModule(
        activeEnterprise,
        "REAL_ESTATE_PROPERTIES",
    );
    const [property, setProperty] = useState(null);
    const [loading, setLoading] = useState(Boolean(property_id));

    const {
        values,
        handleInputChange,
        handleInputChangeOnlyNumbers,
        setFormValues,
        setErrors,
    } = useForm(defaultValues);

    const {
        name,
        source,
        address,
        lat,
        lng,
        client_name,
        client_email,
        client_phone,
        state_name,
        municipality_name,
        colony_name,
        postal_code,
        street,
        lot,
        block,
        interior_number,
        exterior_number,
        property_type_id,
        land_area,
        construction_area,
        has_elevator,
        apartment_floor,
        facade,
        age,
        parking_spaces,
        bedrooms,
        bathrooms,
        half_bathrooms,
        floors_count,
        conservation_id,
        private_amenities,
        common_amenities,
        errors,
    } = values;

    const isEditing = Boolean(property_id);
    const isDepartment = Number(property_type_id) === 5;
    const isCondominium = [4, 5].includes(Number(property_type_id));

    const canRequestFull = property ? property.can_request_avaclick_full : true;
    const propertyReportLinks = getPropertyReportLinks(property);
    const technicalErrors = getPropertyTechnicalErrors(property);

    useEffect(() => {
        if (!canAccessRealEstateProperties) {
            setLoading(false);
            return;
        }
        if (!property_id) {
            setProperty(null);
            setFormValues(defaultValues, true);
            setLoading(false);
            return;
        }

        const loadProperty = () => {
            setLoading(true);
            dispatch(
                startLoadProperty(
                    property_id,
                    (data) => {
                        setProperty(data);
                        setFormValues(getFormValues(data), true);
                        setLoading(false);
                    },
                    () => {
                        navigate("/app/real-estate/properties");
                    }
                )
            );
        };

        loadProperty();
    }, [
        property_id,
        navigate,
        setFormValues,
        dispatch,
        canAccessRealEstateProperties,
    ]);

    const refreshProperty = async (id) => {
        return new Promise((resolve) => {
            dispatch(
                startLoadProperty(
                    id,
                    (data) => {
                        setProperty(data);
                        setFormValues(getFormValues(data), true);
                        resolve(true);
                    },
                    () => resolve(false)
                )
            );
        });
    };

    const returnToList = () => {
        navigate("/app/real-estate/properties");
    };

    const handleSave = async (mode = "save") => {
        const validationErrors = getValidationErrors(values, isEditing, mode);

        if (Object.keys(validationErrors).length > 0) {
            setErrors(validationErrors);
            Swal.fire({
                title: "Formulario incompleto",
                text: "Por favor, completa los campos marcados en rojo.",
                icon: "warning",
                toast: true,
                position: "bottom-end",
                timer: 5000,
            });
            window.scrollTo({ top: 0, behavior: "smooth" });
            return;
        }

        setErrors({});

        const onSuccess = async (savedProperty) => {
            const propertyId = savedProperty?.id || property_id;
            if (propertyId) {
                await refreshProperty(propertyId);
            }

            if (!isEditing && savedProperty?.id) {
                navigate(
                    `/app/real-estate/properties/edit/${savedProperty.id}`,
                );
                return;
            }

            Swal.fire({
                title: "Listo",
                text: "La información se actualizó en la pantalla.",
                icon: "success",
                toast: true,
                position: "bottom-end",
                timer: 5000,
            });
        };

        if (!isEditing) {
            dispatch(startCreate(values, mode, setErrors, onSuccess));
        } else {
            dispatch(startUpdate(values, mode, setErrors, onSuccess));
        }
    };

    const updateLocationFields = ({
        value,
        lat: nextLat,
        lng: nextLng,
        place_id,
        address_components,
    }) => {
        const extractedAddress = extractAddressData(address_components || []);

        setFormValues({
            ...values,
            address: value || "",
            lat: nextLat,
            lng: nextLng,
            place_id: place_id || "",
            address_components: address_components || [],
            state_name: extractedAddress.state_name || values.state_name,
            municipality_name:
                extractedAddress.municipality_name || values.municipality_name,
            colony_name: extractedAddress.colony_name || values.colony_name,
            postal_code: extractedAddress.postal_code || values.postal_code,
            street: extractedAddress.street || values.street,
            exterior_number:
                extractedAddress.exterior_number || values.exterior_number,
        });
    };

    if (loading) {
        return <LoadingApp />;
    }

    return (
        <EnterpriseGuard
            moduleCode="REAL_ESTATE_PROPERTIES"
            title={isEditing ? "Editar propiedad" : "Registrar propiedad"}
        >
            <CardContainer
                title={
                    isEditing
                        ? `Editar propiedad${property?.name ? `: ${property.name}` : ""}`
                        : "Registrar propiedad"
                }
            >
            <Row className="mb-4">
                <Col md={8}>
                    <p className="text-muted mb-0">
                        {isEditing
                            ? "Actualiza el registro básico y completa aquí la información necesaria para solicitar el avalúo completo."
                            : "En esta etapa sólo se pide lo mínimo del avalúo exprés. Al guardar se registra la propiedad y se envía el exprés automáticamente."}
                    </p>
                </Col>
                <Col md={4} className="text-md-end mt-2 mt-md-0">
                    <Button variant="secondary" onClick={returnToList}>
                        Volver al listado
                    </Button>
                </Col>
            </Row>

            <SectionCard title="Identificación del registro" className="mt-3">
                <Row>
                    <Col md={6}>
                        <InputApp
                            title="Nombre"
                            placeholder="Ej. Casa Río Blanco"
                            name="name"
                            value={name}
                            onChange={handleInputChange}
                            errorText={errors?.name?.[0]}
                            required
                        />
                    </Col>

                    <Col md={6}>
                        <InputApp
                            title="Origen"
                            placeholder="AVACLICK"
                            name="source"
                            value={source}
                            onChange={handleInputChange}
                            errorText={errors?.source?.[0]}
                            disabled
                        />
                    </Col>
                </Row>
            </SectionCard>

            <SectionCard
                title="Ubicación del inmueble"
                subtitle="Ubica la propiedad en el mapa y completa la dirección base."
                className="mt-4"
            >
                <div className="text-uppercase text-muted small fw-bold mb-3">
                    Mapa y referencia
                </div>
                <Row>
                    <Col md={12}>
                        <InputGoogleMapsSearchAddress
                            name="address"
                            title="Dirección"
                            placeholder="Busca una dirección o mueve el pin en el mapa"
                            value={address}
                            onChange={handleInputChange}
                            mapHeight="250px"
                            onChangeLocation={updateLocationFields}
                            initialCoordinates={
                                lat !== null && lng !== null
                                    ? { lat: Number(lat), lng: Number(lng) }
                                    : null
                            }
                            errorText={errors?.["payload.address"]?.[0]}
                            confirmationText="Confirma que la imagen muestra el inmueble correcto."
                            required
                        />
                    </Col>
                </Row>

                <div className="text-uppercase text-muted small fw-bold mb-3 mt-4">
                    Dirección desglosada
                </div>
                <Row>
                    <Col md={3}>
                        <InputApp
                            title="Estado"
                            name="state_name"
                            value={state_name}
                            onChange={handleInputChange}
                            errorText={errors?.["payload.state_name"]?.[0]}
                            required={isEditing}
                        />
                    </Col>
                    <Col md={3}>
                        <InputApp
                            title="Municipio"
                            name="municipality_name"
                            value={municipality_name}
                            onChange={handleInputChange}
                            errorText={
                                errors?.["payload.municipality_name"]?.[0]
                            }
                            required={isEditing}
                        />
                    </Col>
                    <Col md={3}>
                        <InputApp
                            title="Colonia"
                            name="colony_name"
                            value={colony_name}
                            onChange={handleInputChange}
                            errorText={errors?.["payload.colony_name"]?.[0]}
                            required={isEditing}
                        />
                    </Col>
                    <Col md={3}>
                        <InputApp
                            title="Código postal"
                            name="postal_code"
                            value={postal_code}
                            onChange={handleInputChangeOnlyNumbers}
                            errorText={errors?.["payload.postal_code"]?.[0]}
                            required={isEditing}
                        />
                    </Col>

                    <Col md={4}>
                        <InputApp
                            title="Calle"
                            name="street"
                            value={street}
                            onChange={handleInputChange}
                            errorText={errors?.["payload.street"]?.[0]}
                            required={isEditing}
                        />
                    </Col>
                    <Col md={2}>
                        <InputApp
                            title="Lote"
                            name="lot"
                            value={lot}
                            onChange={handleInputChange}
                            errorText={errors?.["payload.lot"]?.[0]}
                        />
                    </Col>
                    <Col md={2}>
                        <InputApp
                            title="Manzana"
                            name="block"
                            value={block}
                            onChange={handleInputChange}
                            errorText={errors?.["payload.block"]?.[0]}
                        />
                    </Col>
                    <Col md={2}>
                        <InputApp
                            title="No. interior"
                            name="interior_number"
                            value={interior_number}
                            onChange={handleInputChange}
                            errorText={errors?.["payload.interior_number"]?.[0]}
                        />
                    </Col>
                    <Col md={2}>
                        <InputApp
                            title="No. exterior"
                            name="exterior_number"
                            value={exterior_number}
                            onChange={handleInputChange}
                            errorText={errors?.["payload.exterior_number"]?.[0]}
                        />
                    </Col>
                </Row>
            </SectionCard>

            <SectionCard
                title="Datos para avalúo exprés"
                subtitle="Aquí va la captura mínima obligatoria para registrar y disparar el exprés."
                className="mt-4"
            >
                <div className="text-uppercase text-muted small fw-bold mb-3">
                    Clasificación
                </div>
                <Row>
                    <Col md={4}>
                        <SelectSearchApp
                            title="Tipo de inmueble"
                            name="property_type_id"
                            value={property_type_id}
                            onChange={handleInputChange}
                            options={AVACLICK_PROPERTY_TYPES_OPTIONS}
                            errorText={
                                errors?.["payload.property_type_id"]?.[0]
                            }
                            required
                        />
                    </Col>
                    <Col md={4}>
                        <SelectSearchApp
                            title="Conservación"
                            name="conservation_id"
                            value={conservation_id}
                            onChange={handleInputChange}
                            options={AVACLICK_CONSERVATION_OPTIONS}
                            errorText={errors?.["payload.conservation_id"]?.[0]}
                            required
                        />
                    </Col>
                </Row>

                <div className="text-uppercase text-muted small fw-bold mb-3 mt-4">
                    Sobre el inmueble
                </div>
                <Row>
                    <Col md={4}>
                        <InputApp
                            title="m² terreno"
                            type="number"
                            min="0"
                            step="any"
                            name="land_area"
                            value={land_area}
                            onChange={handleInputChange}
                            errorText={errors?.["payload.land_area"]?.[0]}
                            disabled={isDepartment}
                        />
                    </Col>
                    <Col md={4}>
                        <InputApp
                            title="m² construcción"
                            type="number"
                            min="0"
                            step="any"
                            name="construction_area"
                            value={construction_area}
                            onChange={handleInputChange}
                            errorText={
                                errors?.["payload.construction_area"]?.[0]
                            }
                            infoText="Si no lo conoces, puedes dejarlo vacío y Avaclick intentará estimarlo."
                        />
                    </Col>
                </Row>

                <div className="text-uppercase text-muted small fw-bold mb-3 mt-4">
                    Espacios
                </div>
                <Row>
                    <Col md={3}>
                        <InputApp
                            title="Niveles"
                            type="number"
                            min="0"
                            name="floors_count"
                            value={floors_count}
                            onChange={handleInputChangeOnlyNumbers}
                            errorText={errors?.["payload.floors_count"]?.[0]}
                            required
                        />
                    </Col>

                    <Col md={3}>
                        <InputApp
                            title="Recámaras"
                            type="number"
                            min="0"
                            name="bedrooms"
                            value={bedrooms}
                            onChange={handleInputChangeOnlyNumbers}
                            errorText={errors?.["payload.bedrooms"]?.[0]}
                            required
                        />
                    </Col>
                    <Col md={3}>
                        <InputApp
                            title="Baños"
                            type="number"
                            min="0"
                            name="bathrooms"
                            value={bathrooms}
                            onChange={handleInputChangeOnlyNumbers}
                            errorText={errors?.["payload.bathrooms"]?.[0]}
                            required
                        />
                    </Col>
                    <Col md={3}>
                        <InputApp
                            title="Medios baños"
                            type="number"
                            min="0"
                            name="half_bathrooms"
                            value={half_bathrooms}
                            onChange={handleInputChangeOnlyNumbers}
                            errorText={errors?.["payload.half_bathrooms"]?.[0]}
                        />
                    </Col>
                </Row>

                {!isEditing && (
                    <Row className="mt-3">
                        <Col md={12}>
                            <div className="alert alert-info mb-0">
                                Después de guardar podrás abrir el registro y
                                capturar datos adicionales del cliente,
                                amenidades y atributos para solicitar el avalúo
                                completo.
                            </div>
                        </Col>
                    </Row>
                )}
            </SectionCard>

            {isEditing && (
                <>
                    <SectionCard title="Datos del cliente" className="mt-4">
                        <Row>
                            <Col md={4}>
                                <InputApp
                                    title="Nombre cliente"
                                    name="client_name"
                                    value={client_name}
                                    onChange={handleInputChange}
                                    errorText={
                                        errors?.["payload.client_name"]?.[0]
                                    }
                                    required
                                />
                            </Col>
                            <Col md={4}>
                                <InputApp
                                    title="Correo cliente"
                                    name="client_email"
                                    value={client_email}
                                    onChange={handleInputChange}
                                    errorText={
                                        errors?.["payload.client_email"]?.[0]
                                    }
                                    required
                                />
                            </Col>
                            <Col md={4}>
                                <InputApp
                                    title="Teléfono cliente"
                                    name="client_phone"
                                    value={client_phone}
                                    onChange={handleInputChangeOnlyNumbers}
                                    errorText={
                                        errors?.["payload.client_phone"]?.[0]
                                    }
                                    required
                                />
                            </Col>
                        </Row>
                    </SectionCard>

                    <SectionCard
                        title="Complementos del inmueble"
                        className="mt-4"
                    >
                        <Row>
                            <Col md={4}>
                                <InputApp
                                    title="Fachada"
                                    name="facade"
                                    value={facade}
                                    onChange={handleInputChange}
                                    errorText={errors?.["payload.facade"]?.[0]}
                                />
                            </Col>
                            <Col md={4}>
                                <InputApp
                                    title="Edad"
                                    type="number"
                                    min="0"
                                    name="age"
                                    value={age}
                                    onChange={handleInputChangeOnlyNumbers}
                                    errorText={errors?.["payload.age"]?.[0]}
                                />
                            </Col>
                            <Col md={4}>
                                <InputApp
                                    title="Cocheras"
                                    type="number"
                                    min="0"
                                    name="parking_spaces"
                                    value={parking_spaces}
                                    onChange={handleInputChangeOnlyNumbers}
                                    errorText={
                                        errors?.["payload.parking_spaces"]?.[0]
                                    }
                                />
                            </Col>

                            <Col md={4} className="d-flex align-items-end">
                                <CheckBoxApp
                                    name="has_elevator"
                                    label="Tiene elevador"
                                    checked={has_elevator}
                                    onChange={handleInputChange}
                                />
                            </Col>
                            <Col md={4}>
                                <InputApp
                                    title="Piso departamento"
                                    type="number"
                                    min="0"
                                    name="apartment_floor"
                                    value={apartment_floor}
                                    onChange={handleInputChangeOnlyNumbers}
                                    errorText={
                                        errors?.["payload.apartment_floor"]?.[0]
                                    }
                                    disabled={!isDepartment}
                                />
                            </Col>
                        </Row>
                    </SectionCard>

                    <SectionCard
                        title="Amenidades en la vivienda"
                        className="mt-4"
                    >
                        <Row>
                            <Col md={12}>
                                <SelectSearchApp
                                    title="Amenidades de la vivienda"
                                    name="private_amenities"
                                    value={private_amenities}
                                    onChange={handleInputChange}
                                    options={AVACLICK_PRIVATE_AMENITIES_OPTIONS}
                                    errorText={
                                        errors?.[
                                            "payload.private_amenities"
                                        ]?.[0]
                                    }
                                    multiple
                                    closeMenuOnSelect={false}
                                />
                            </Col>
                        </Row>
                    </SectionCard>

                    <SectionCard
                        title="Amenidades del condominio"
                        className="mt-4"
                    >
                        <Row>
                            <Col md={12}>
                                <SelectSearchApp
                                    title="Amenidades comunes"
                                    name="common_amenities"
                                    value={common_amenities}
                                    onChange={handleInputChange}
                                    options={AVACLICK_COMMON_AMENITIES_OPTIONS}
                                    errorText={
                                        errors?.[
                                            "payload.common_amenities"
                                        ]?.[0]
                                    }
                                    multiple
                                    closeMenuOnSelect={false}
                                    disabled={!isCondominium}
                                />
                            </Col>
                        </Row>
                    </SectionCard>
                </>
            )}

            {property && (
                <>
                    <SectionCard
                        title="Seguimiento de solicitudes Avaclick"
                        className="mt-4"
                    >
                        <Row>
                            <Col md={4}>
                                <StatusBadge
                                    label="Exprés"
                                    status={property.avaclick_express_status}
                                />
                                <small className="text-muted d-block">
                                    Solicitado:{" "}
                                    {formatDateTime(
                                        property.avaclick_express_requested_at,
                                    )}
                                </small>
                                <small className="text-muted d-block">
                                    Finalizado:{" "}
                                    {formatDateTime(
                                        property.avaclick_express_completed_at,
                                    )}
                                </small>
                            </Col>

                            <Col md={6}>
                                <StatusBadge
                                    label="Completo"
                                    status={property.avaclick_full_status}
                                />
                                <small className="text-muted d-block">
                                    Solicitado:{" "}
                                    {formatDateTime(
                                        property.avaclick_full_requested_at,
                                    )}
                                </small>
                                <small className="text-muted d-block">
                                    Fecha avalúo:{" "}
                                    {formatDateTime(
                                        property.avaclick_appraisal_date,
                                    )}
                                </small>
                                {!canRequestFull &&
                                    property.next_avaclick_full_request_at && (
                                        <small className="text-muted d-block">
                                            Reenviar después de:{" "}
                                            {formatDateTime(
                                                property.next_avaclick_full_request_at,
                                            )}
                                        </small>
                                    )}
                            </Col>
                        </Row>
                    </SectionCard>

                    <SectionCard
                        title="Resultados de valoración profesional"
                        className="mt-4"
                    >
                        {propertyReportLinks.length ? (
                            <div className="mb-4">
                                {propertyReportLinks.map((report) => (
                                    <ProminentReportLink
                                        key={report.key}
                                        label={report.label}
                                        url={report.url}
                                    />
                                ))}
                            </div>
                        ) : null}

                        {technicalErrors.length ? (
                            <div className="mb-4">
                                <TechnicalMessageList
                                    messages={technicalErrors}
                                    variant="danger"
                                    title="Avisos del sistema"
                                />
                            </div>
                        ) : null}

                        <Accordion
                            alwaysOpen
                            defaultActiveKey={[
                                "express-response",
                                "full-response",
                            ]}
                            className="mt-3"
                        >
                            <TechnicalResponseAccordionItem
                                eventKey="express-response"
                                title="Respuesta exprés"
                                data={property.avaclick_express_response}
                                emptyText="Sin respuesta exprés registrada."
                            />
                            <TechnicalResponseAccordionItem
                                eventKey="full-response"
                                title="Respuesta completa"
                                data={property.avaclick_full_response}
                                emptyText="Sin respuesta completa registrada."
                            />
                        </Accordion>
                    </SectionCard>
                </>
            )}

            <Row className="mt-4">
                {Object.keys(errors).length > 0 ? (
                    <Col md={12} className="mb-3">
                        <div className="alert alert-danger d-flex align-items-center mb-0">
                            <IconApp iconClassName="fa fa-exclamation-triangle me-2" />
                            <div>
                                <strong>Formulario incompleto:</strong> Faltan datos requeridos o hay errores. Sube para revisar los campos marcados en rojo.
                            </div>
                        </div>
                    </Col>
                ) : null}
                <Col
                    md={12}
                    className="d-flex flex-wrap justify-content-end gap-2"
                >
                    {!isEditing ? (
                        <Button
                            variant="primary"
                            className="btn-app-primary"
                            onClick={() => handleSave("express")}
                        >
                            Registrar básico y solicitar exprés
                            <IconApp iconClassName="fa fa-bolt ms-2" />
                        </Button>
                    ) : (
                        <>
                            <Button
                                variant="outline-primary"
                                onClick={() => handleSave("save")}
                            >
                                Guardar cambios
                                <IconApp iconClassName="fa fa-save ms-2" />
                            </Button>

                            <Button
                                variant="success"
                                onClick={() => handleSave("full")}
                                disabled={!canRequestFull}
                            >
                                Guardar y solicitar completo
                                <IconApp iconClassName="fa fa-file-signature ms-2" />
                            </Button>
                        </>
                    )}
                </Col>
            </Row>
            </CardContainer>
        </EnterpriseGuard>
    );
}
