import {
  Grid,
  Box,
  Button,
  Checkbox,
  CircularProgress,
  FormControlLabel,
  FormGroup,
  Stack,
} from "@mui/material";
import axios from "axios";
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";

const LOSS_FIELDS = [
  {
    key: "includeTotalDiseaseLosses",
    apiKey: "include_total_disease_losses",
    label: "مجموع تلفات ناشی از بیماری",
  },
  {
    key: "includeTotalFlockDestruction",
    apiKey: "include_total_flock_destruction",
    label: "مجموع معدوم‌سازی گله",
  },
  {
    key: "includeTotalNormalFlockLosses",
    apiKey: "include_total_normal_flock_losses",
    label: "مجموع تلفات عادی گله",
  },
  {
    key: "includeTotalForceMajeureLosses",
    apiKey: "include_total_force_majeure_losses",
    label: "مجموع تلفات ناشی از عوامل قهری و طبیعی",
  },
  {
    key: "includeTotalFireLosses",
    apiKey: "include_total_fire_losses",
    label: "مجموع تلفات ناشی از آتش‌سوزی",
  },
];

const DEFAULT_FORM_STATE = LOSS_FIELDS.reduce(
  (acc, { key }) => ({ ...acc, [key]: false }),
  {}
);

export const ManageEvacuations = () => {
  const [openNotif] = useContext(AppContext);
  const notify = useCallback(
    ({ severity, msg, vertical = "top", horizontal = "center" }) =>
      openNotif({
        severity,
        msg,
        vertical,
        horizontal,
      }),
    [openNotif]
  );
  const [formState, setFormState] = useState(DEFAULT_FORM_STATE);
  const [recordId, setRecordId] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    const fetchLossManagement = async () => {
      setIsLoading(true);

      try {
        const { data } = await axios.get("hatching-loss-management/");

        setRecordId(data?.id ?? null);

        setFormState((prev) =>
          LOSS_FIELDS.reduce(
            (acc, { key }) => ({
              ...acc,
              [key]: Boolean(data?.[key]),
            }),
            { ...prev }
          )
        );
      } catch (error) {
        const errorText =
          error?.response?.data?.detail ??
          error?.response?.data?.message ??
          error?.message ??
          "خطایی در دریافت اطلاعات رخ داده است.";
        notify({ severity: "error", msg: errorText });
      } finally {
        setIsLoading(false);
      }
    };

    fetchLossManagement();
  }, []);

  const handleChange = (fieldKey) => (event) => {
    const { checked } = event.target;
    setFormState((prev) => ({
      ...prev,
      [fieldKey]: checked,
    }));
  };

  const requestBody = useMemo(
    () =>
      LOSS_FIELDS.reduce((acc, { key, apiKey }) => {
        acc[apiKey] = Boolean(formState[key]);
        return acc;
      }, {}),
    [formState]
  );

  const handleSubmit = async (event) => {
    event.preventDefault();

    setIsSaving(true);

    const targetId = recordId ?? 1;

    try {
      await axios.patch(`hatching-loss-management/${targetId}/`, requestBody);

      notify({
        severity: "success",
        msg: "اطلاعات با موفقیت به‌روزرسانی شد.",
      });
    } catch (error) {
      const errorText =
        error?.response?.data?.detail ??
        error?.response?.data?.message ??
        error?.message ??
        "خطایی در به‌روزرسانی اطلاعات رخ داده است.";
      notify({ severity: "error", msg: errorText });
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <Grid
      component="section"
      xs={12}
      style={{ padding: "20px", width: "100%" }}
    >
      {isLoading ? (
        <Stack direction="row" justifyContent="center">
          <CircularProgress />
        </Stack>
      ) : (
        <Grid component="form" onSubmit={handleSubmit} xs={12}>
          <FormGroup>
            {LOSS_FIELDS.map(({ key, label }) => (
              <FormControlLabel
                key={key}
                control={
                  <Checkbox
                    checked={Boolean(formState[key])}
                    onChange={handleChange(key)}
                    name={key}
                    disabled={isSaving}
                  />
                }
                label={label}
              />
            ))}
          </FormGroup>

          <Box>
            <Button
              type="submit"
              variant="contained"
              disabled={isSaving}
              color="primary"
            >
              {isSaving ? "در حال ذخیره..." : "به‌روزرسانی"}
            </Button>
          </Box>
        </Grid>
      )}
    </Grid>
  );
};
