import {
  Button,
  FormControlLabel,
  IconButton,
  Switch,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import {
  CLOSE_MODAL,
  DRAWER,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { slaughterGetKillerKillhousesService } from "../../../slaughter-house/services/slaughter-get-killers-killhouses";
import { provinceGetSlaughterhousesQuotaService } from "../../services/province-get-slaughterhouses-quota";
import { provincePurgeNeededRequestService } from "../../services/province-purge-needed-request";
import { ProvinceCreateKillhouse } from "../province-create-killhouse/ProvinceCreateKillhouse";
import { ProvinceSelectSlaughterForSlaughter } from "../province-select-slaughter-for-slaughter/ProvinceSelectSlaughterForSlaughter";
import { ProvinceUpdateSlaughterIdentity } from "../province-update-slaughter-identity/ProvinceUpdateSlaughterIdentity";
import EditIcon from "@mui/icons-material/Edit";
import axios from "axios";
import { ProvinceUpdateKillerIdentity } from "../province-update-killer-identity/ProvinceUpdateKillerIdentity";
import { RiFileExcel2Fill } from "react-icons/ri";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
export const ProvinceManageSlaughterKillplace = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [dataTable, setDataTable] = useState();
  const { provinceGetSlaughterhousesQuota } = useSelector(
    (state) => state.provinceSlice
  );

  useEffect(() => {
    dispatch(provinceGetSlaughterhousesQuotaService());
    dispatch(slaughterGetKillerKillhousesService());
  }, []);

  useEffect(() => {
    const d = provinceGetSlaughterhousesQuota?.map((item, i) => {
      const killhouseType = item?.killHouse?.killer ? "Killer" : "KillHouse";
      return [
        i + 1,
        getRoleFromUrl() === "ProvinceOperator" ? (
          item?.killHouse?.killer ? (
            "کشتارکن"
          ) : (
            "کشتارگاه"
          )
        ) : (
          <ProvinceUpdateSlaughterIdentity
            killhouseType={killhouseType}
            slaughterKey={item.key}
            key={i}
          />
        ),
        getRoleFromUrl() === "ProvinceOperator" ? (
          item?.killHouse?.killer ? (
            item?.killHouse?.type === "public" ? (
              "عمومی"
            ) : (
              "اختصاصی"
            )
          ) : (
            "-"
          )
        ) : (
          <ProvinceUpdateKillerIdentity
            killerType={item?.killHouse?.type}
            disableSelect={killhouseType === "KillHouse"}
            slaughterKey={item?.killHouse?.key}
            key={i}
          />
        ),
        <Grid key={item.key} alignItems="center" justifyContent="center">
          <Typography variant="caption">{item.killHouse?.name}</Typography>
          <IconButton
            size="small"
            color="primary"
            aria-label="Delete"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ویرایش",
                  content: (
                    <EditKillhouseUnitName
                      key={item.key}
                      name={item.killHouse?.name}
                      item={item}
                    />
                  ),
                })
              );
            }}
          >
            <EditIcon fontSize="10px" />
          </IconButton>
        </Grid>,
        <Grid
          container
          key={item.key}
          alignItems="center"
          justifyContent="center"
        >
          <Typography variant="caption">
            {item.killHouse?.killHouseOperator?.user?.fullname} (
            {item.killHouse?.killHouseOperator?.user?.mobile})
          </Typography>
          <IconButton
            size="small"
            color="primary"
            aria-label="Delete"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ویرایش",
                  content: <EditKillhouseOwner key={item.key} item={item} />,
                })
              );
            }}
          >
            <EditIcon fontSize="10px" />
          </IconButton>
        </Grid>,
        item.killHouseVet
          ? `${item.killHouseVet?.vet?.user?.fullname} (${item.killHouseVet?.vet?.user?.mobile})`
          : "-",
        `${item.killHouse?.systemAddress?.province?.name} - ${item.killHouse?.systemAddress?.city?.name} - ${item.killHouse?.systemAddress?.address}`,
        item?.killHouse?.killer ? (
          <ProvinceSelectSlaughterForSlaughter
            key={item.killHouse?.name + i}
            slaughterKey={item.key}
            killHouseForKiller={item.killHouseForKiller}
            disabled={false}
          />
        ) : (
          item.killHouse?.name
        ),
        <KillhouseStatus key={item.key} item={item} />,
      ];
    });

    setDataTable(d);
  }, [provinceGetSlaughterhousesQuota]);

  return (
    <Grid mt={SPACING.SMALL}>
      <Grid container justifyContent="space-between" mb={SPACING.SMALL}>
        <Grid>
          <Button
            variant="contained"
            onClick={() => {
              dispatch(
                DRAWER({
                  right: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                  title: "ایجاد خریدار",
                  content: <ProvinceCreateKillhouse />,
                })
              );
            }}
          >
            ایجاد خریدار
          </Button>

          <Tooltip title="خروجی اکسل">
            <a
              href={`${axios.defaults.baseURL}kill_house_user_excel`}
              rel="noreferrer"
            >
              <Button color="success">
                <RiFileExcel2Fill size={32} />
              </Button>
            </a>
          </Tooltip>
        </Grid>
        <Button
          variant="contained"
          onClick={() => {
            dispatch(provincePurgeNeededRequestService()).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        >
          پاکسازی اعلام نیاز
        </Button>
      </Grid>
      <ResponsiveTable
        paginated
        title="کشتارگاه ها"
        columns={[
          "ردیف",
          "ماهیت",
          "نوع کشتارکن",
          "نام واحد",
          "نام و نام خانوادگی (تلفن)",
          "دامپزشک کشتارگاه (تلفن)",
          "آدرس",
          "محل کشتار",
          "وضعیت",
        ]}
        data={dataTable}
      />
    </Grid>
  );
};

const KillhouseStatus = ({ item }) => {
  const dispatch = useDispatch();
  const [isChecked, setIsChecked] = useState(item.killHouse.active);

  const handleSwitchChange = (event) => {
    setIsChecked(event.target.checked);
    const apiUrl = `${axios.defaults.baseURL}kill_house/0/`;

    const postData = {
      kill_house_key: item.killHouse.key,
      active: event.target.checked,
    };

    axios
      .put(apiUrl, postData)
      .then(() => {
        dispatch(provinceGetSlaughterhousesQuotaService());
        dispatch(slaughterGetKillerKillhousesService());
        dispatch(CLOSE_MODAL());
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  };

  return (
    <FormControlLabel
      control={
        <Switch
          checked={isChecked}
          onChange={handleSwitchChange}
          color="primary"
        />
      }
      label={isChecked ? "فعال" : "غیرفعال"}
    />
  );
};

const EditKillhouseUnitName = ({ name, item }) => {
  const dispatch = useDispatch();
  const [inputValue, setInputValue] = useState(name);

  const handleInputChange = (event) => {
    setInputValue(event.target.value);
  };

  return (
    <Grid container gap={SPACING.TINY}>
      <TextField
        label="نام واحد"
        variant="outlined"
        fullWidth
        value={inputValue}
        onChange={handleInputChange}
      />
      <Button
        variant="contained"
        fullWidth
        onClick={() => {
          const apiUrl = `${axios.defaults.baseURL}kill_house/0/`;

          const postData = {
            kill_house_key: item.killHouse.key,
            name: inputValue,
          };

          axios
            .put(apiUrl, postData)
            .then(() => {
              dispatch(provinceGetSlaughterhousesQuotaService());
              dispatch(slaughterGetKillerKillhousesService());
              dispatch(CLOSE_MODAL());
            })
            .catch((error) => {
              console.error("Error:", error);
            });
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};

const EditKillhouseOwner = ({ item }) => {
  const dispatch = useDispatch();
  const [firstName, setFirstName] = useState(
    item.killHouse?.killHouseOperator?.user?.firstName
  );
  const [lastName, setLastName] = useState(
    item.killHouse?.killHouseOperator?.user?.lastName
  );
  const [mobile, setMobile] = useState(
    item.killHouse?.killHouseOperator?.user?.mobile
  );

  const firstNameChange = (event) => {
    setFirstName(event.target.value);
  };

  const lastNameChange = (event) => {
    setLastName(event.target.value);
  };

  const mobileChange = (event) => {
    setMobile(event.target.value);
  };

  return (
    <Grid container gap={SPACING.SMALL}>
      <TextField
        label="نام"
        variant="outlined"
        fullWidth
        value={firstName}
        onChange={firstNameChange}
      />
      <TextField
        label="نام خانوادگی"
        variant="outlined"
        fullWidth
        value={lastName}
        onChange={lastNameChange}
      />
      <TextField
        label="تلفن"
        variant="outlined"
        fullWidth
        value={mobile}
        onChange={mobileChange}
      />
      <Button
        variant="contained"
        fullWidth
        onClick={() => {
          const apiUrl = `${axios.defaults.baseURL}kill_house/0/`;

          const postData = {
            kill_house_key: item.killHouse.key,
            first_name: firstName,
            last_name: lastName,
            mobile: mobile,
          };

          axios
            .put(apiUrl, postData)
            .then(() => {
              dispatch(provinceGetSlaughterhousesQuotaService());
              dispatch(slaughterGetKillerKillhousesService());
              dispatch(CLOSE_MODAL());
            })
            .catch((error) => {
              console.error("Error:", error);
            });
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
