import React, { ReactNode, useEffect, useState } from "react";
import ConfirmationModal from "../../UI/Modal/ActionsModal/ConfirmationModal";
import isEqual from "lodash/isEqual";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import CustomFormSection from "../../UI/Forms/CustomFormSection/CustomFormSection";
import CustomLabel from "../../UI/Forms/CustomLabel/CustomLabel";
import CustomDatePicker from "../../UI/Forms/CustomDateTimePicker/CustomDatePicker";
import dayjs, { Dayjs } from "dayjs";
import Add from "../../../assets/images/plus_small.svg";
import Remove from "../../../assets/images/minus_small.svg";
import CustomTextField from "../../UI/Forms/CustomTextField/CustomTextField";
import useLoading from "../../../hooks/useLoading";
import {WithRule, WithRuleBoolean} from "../../HOC/WithRule";

type Snapshot = {
    title: string;
    date: Dayjs | null;
};

type EditSnapshotsModalProps = {
    children?: ReactNode;
    close: () => void;
    editSnapshots: (snapshots: Snapshot[]) => void;
    oldSnapshots: Snapshot[];

    projectCode:string | number
};

const EditSnapshotsModal = ({
                                editSnapshots,
                                projectCode='',
                                close,
                                oldSnapshots,
                            }: EditSnapshotsModalProps) => {
    const [loading, setIsLoading] = useLoading(false);
    const [snapshots, setSnapshots] = useState<Snapshot[]>(
        oldSnapshots.length > 0 ? oldSnapshots : []
    );

    useEffect(() => {
        setSnapshots(oldSnapshots.length > 0 ? oldSnapshots : []);
    }, [oldSnapshots]);

    const lastDateIndex = snapshots.length - 1;

    const addDate = () => {
        setIsLoading(true);
        setSnapshots((prev) => [...prev, { title: "", date: null }]);
        setIsLoading(false);
    };

    const removeDate = (indexToRemove: number) => {
        setIsLoading(true);
        setSnapshots((prev) => prev.filter((_, i) => i !== indexToRemove));
        setIsLoading(false);
    };

    const updateSnapshot = (index: number, field: keyof Snapshot, value: any) => {
        setSnapshots((prev) =>
            prev.map((s, i) => (i === index ? { ...s, [field]: value } : s))
        );
    };

    // ---------------------------
    // Submit button logic
    // ---------------------------

    // Check if all snapshots are fully filled
    const isSnapshotsValid = snapshots.every(
        (s) => s.title.trim() !== "" && s.date !== null
    );

    /**
     * Disable submit if:
     * 1️⃣ Nothing changed compared to oldSnapshots
     * 2️⃣ OR there are partially filled snapshots (title/date missing) AND at least one snapshot exists
     *
     * Notes:
     * - Removing the last snapshot will leave an empty row.
     * - Since oldSnapshots had content, `isEqual` is false → submit enabled.
     * - Adding a new snapshot disables submit until fields are filled.
     */
    const isDisabled =
        isEqual(oldSnapshots, snapshots) ||
        (snapshots.some((s) => s.title.trim() === "" || s.date === null) &&
            // only disable if the row is a newly added incomplete snapshot or partially filled
            snapshots.length > 0 && !(snapshots.length === 1 && oldSnapshots.length === 1 && oldSnapshots[0] !== undefined)
        );

    const canEditSnapshots = WithRuleBoolean( "snapshots");
    const canEditSnapshotsReverse = !canEditSnapshots

    return (
        <ConfirmationModal
            onClose={close}
            title={(canEditSnapshots ?'Ορισμός' : 'Προβολή') + ' Σημείων Αναφοράς'}
            text={canEditSnapshotsReverse ? 'Παρακάτω βλέπετε τα Σημεία Αναφοράς του έργου '+ projectCode :'Παρακάτω διαμορφώνετε και βλέπετε τα σημεία αναφοράς για το έργο ' + projectCode + '.'}
            modalAction={() => editSnapshots(snapshots)}
            className={"edit-snapshots"}
            FormButtonCancelText={"ΑΚΥΡΩΣΗ"}
            FormButtonSubmitText={"ΑΠΟΘΗΚΕΥΣΗ"}
            isDisabled={isDisabled || canEditSnapshotsReverse}
            jokerProp={canEditSnapshotsReverse}
        >
            <div className={"form mb-6"}>
                <LocalizationProvider dateAdapter={AdapterDayjs}>
                    <CustomFormSection
                        styles={{
                            overflowY: "auto",
                            overflowX: "hidden",
                            height: "100%",
                            maxHeight: "277px",
                        }}
                        theme={"default"}
                    >
                        {snapshots.length === 0 ? (
                            // ✅ Show only ADD button
                            <WithRule target="snapshots">
                                <div className="d-flex justify-content-center">
                                    <button
                                        disabled={loading}
                                        type="button"
                                        className="randevouz-buttons"
                                        onClick={addDate}
                                    >
                                        <img
                                            style={{ filter: "var(--svg-default)" }}
                                            src={Add}
                                            alt="add"
                                        />
                                    </button>
                                </div>
                            </WithRule>
                        ) : (
                            // ✅ Existing rendering for snapshot rows
                            snapshots.map((snapshot, index) => (
                                <div
                                    className={`row gy-5 gx-5 ${
                                        index < snapshots.length - 1 ? "mb-4" : ""
                                    }`}
                                    key={index}
                                >
                                    <div className="col-6">
                                        <CustomLabel req={true}>ΤΙΤΛΟΣ</CustomLabel>
                                        <CustomTextField
                                            readOnly={canEditSnapshotsReverse}
                                            id={`snapshot_title_${index}`}
                                            value={snapshot.title}
                                            onChange={(value: string) =>
                                                updateSnapshot(index, "title", value)
                                            }
                                        />
                                    </div>

                                    <div className="col-5">
                                        <CustomLabel req={true}>ΗΜΕΡΟΜΗΝΙΑ</CustomLabel>
                                        <CustomDatePicker
                                            readOnly={canEditSnapshotsReverse}
                                            minDate={dayjs()}
                                            value={snapshot.date}
                                            onChange={(newValue: Dayjs | null) =>
                                                updateSnapshot(index, "date", newValue)
                                            }
                                        />
                                    </div>

                                    <WithRule target="snapshots">
                                        <div className="col-1 d-flex align-items-end gap-5">
                                            {/* REMOVE button */}
                                            <button
                                                disabled={loading}
                                                type="button"
                                                className="randevouz-buttons col-lg-1"
                                                onClick={() => removeDate(index)}
                                            >
                                                <img
                                                    style={{ filter: "var(--svg-default)" }}
                                                    src={Remove}
                                                    alt="remove"
                                                />
                                            </button>

                                            {/* ADD button only on last row */}
                                            {index === lastDateIndex && (
                                                <button
                                                    disabled={loading}
                                                    type="button"
                                                    className="randevouz-buttons col-lg-1"
                                                    onClick={addDate}
                                                >
                                                    <img
                                                        style={{ filter: "var(--svg-default)" }}
                                                        src={Add}
                                                        alt="add"
                                                    />
                                                </button>
                                            )}
                                        </div>
                                    </WithRule>
                                </div>
                            ))
                        )}
                    </CustomFormSection>

                </LocalizationProvider>
            </div>
        </ConfirmationModal>
    );
};

export default EditSnapshotsModal;
