import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  Tab,
  Tabs,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { VetFarmSubmitFarmInfoForm } from "../../../vet-farm/components/vet-farm-submit-farm-info-form/VetFarmSubmitFarmInfoForm";
import { SPACING } from "../../../../data/spacing";
import { InspectorAddVetToKillHouse } from "../inspector-add-vet-to-kill-house/InspectorAddVetToKillHouse";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import axios from "axios";
import { RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import TuneIcon from "@mui/icons-material/Tune";
import AddBusinessIcon from "@mui/icons-material/AddBusiness";
import FileDownloadIcon from "@mui/icons-material/FileDownload";
import AddHomeWorkIcon from "@mui/icons-material/AddHomeWork";

export const ManageFarmComponent = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);
  const [selectedTab, setSelectedTab] = useState(0);

  const handleTabChange = (event, newValue) => {
    setSelectedTab(newValue);
  };

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());

    const vetFarmParam =
      selectedTab === 0
        ? "&vet_farm=true"
        : selectedTab === 2 // تب کشتارگاه حالا سومین تب است (ایندکس 2)
        ? "&vet_farm=false"
        : ""; // تب بدون فارم (ایندکس 1) پارامتر خاصی ندارد

    try {
      const response = await axios.get(
        `vet/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}${vetFarmParam}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching users", error);
    } finally {
      dispatch(LOADING_END());
    }
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    setPage(1);
    fetchApiData(1);
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const VetFarmActions = ({ vetFarm }) => {
    const [anchorEl, setAnchorEl] = useState(null);
    const open = Boolean(anchorEl);

    const handleOpen = (event) => {
      setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
      setAnchorEl(null);
    };

    const handleRegisterFarm = () => {
      dispatch(
        DRAWER({
          right: !(window.innerWidth <= 600),
          bottom: window.innerWidth <= 600,
          title: "ثبت فارم",
          content: (
            <VetFarmSubmitFarmInfoForm
              item={vetFarm}
              vetFarmKey={vetFarm.key}
              updateTable={updateTable}
            />
          ),
        })
      );
      handleClose();
    };

    const handleDownloadExcel = () => {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "فایل اکسل در حال دانلود می باشد، این عملیات ممکن است زمان بر باشد لطفا صبر کنید.",
        severity: "success",
      });
      const link = `${axios.defaults.baseURL}technical_responsible_performance_excel/?key=${vetFarm?.key}`;
      window.location.href = link;
      handleClose();
    };

    return (
      <Grid>
        <Tooltip title="تنظیمات">
          <IconButton
            color="primary"
            className="avicultureActiveRequestsBtn"
            onClick={handleOpen}
          >
            <TuneIcon />
          </IconButton>
        </Tooltip>
        <Popover
          open={open}
          anchorEl={anchorEl}
          onClose={handleClose}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "right",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left",
          }}
        >
          <List sx={{ minWidth: 180, p: 1 }}>
            <ListItemButton onClick={handleRegisterFarm} sx={{ py: 1 }}>
              <ListItemIcon>
                <AddBusinessIcon color="primary" />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" color="textPrimary">
                    ثبت فارم
                  </Typography>
                }
              />
            </ListItemButton>
            <ListItemButton onClick={handleDownloadExcel} sx={{ py: 1 }}>
              <ListItemIcon>
                <FileDownloadIcon color="success" />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" color="textPrimary">
                    خروجی اکسل
                  </Typography>
                }
              />
            </ListItemButton>
          </List>
        </Popover>
      </Grid>
    );
  };

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };
  const KillHouseActions = ({ vet }) => {
    const [anchorEl, setAnchorEl] = useState(null);
    const open = Boolean(anchorEl);

    const handleOpen = (event) => {
      setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
      setAnchorEl(null);
    };

    const handleRegisterKillHouse = () => {
      dispatch(
        DRAWER({
          right: !(window.innerWidth <= 600),
          bottom: window.innerWidth <= 600,
          title: "ثبت کشتارگاه",
          content: (
            <InspectorAddVetToKillHouse item={vet} userKey={vet.user.key} />
          ),
        })
      );
      handleClose();
    };

    return (
      <Grid>
        <Tooltip title="تنظیمات">
          <IconButton
            color="primary"
            className="avicultureActiveRequestsBtn"
            onClick={handleOpen}
          >
            <TuneIcon />
          </IconButton>
        </Tooltip>
        <Popover
          open={open}
          anchorEl={anchorEl}
          onClose={handleClose}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "right",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left",
          }}
        >
          <List sx={{ minWidth: 180, p: 1 }}>
            <ListItemButton onClick={handleRegisterKillHouse} sx={{ py: 1 }}>
              <ListItemIcon>
                <AddHomeWorkIcon color="primary" />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" color="textPrimary">
                    ثبت کشتارگاه
                  </Typography>
                }
              />
            </ListItemButton>
          </List>
        </Popover>
      </Grid>
    );
  };

  useEffect(() => {
    fetchApiData(1);
  }, [dispatch, perPage, selectedTab]);

  useEffect(() => {
    const d = data?.map((item, i) => {
      const index = page === 1 ? i + 1 : i + perPage * (page - 1) + 1;
      const baseInfo = [
        index,
        item.user.fullname,
        item.user.nationalId,
        item.user.mobile,
        item.user.province,
        item.user.city,
      ];

      if (selectedTab === 0) {
        return [
          ...baseInfo,
          <Grid
            container
            alignItems="baseline"
            xs={12}
            key={i}
            spacing={2}
            mt={1}
            mb={1}
          >
            {item?.farms?.length
              ? item?.farms.map((option, idx) => (
                  <Grid
                    container
                    direction="column"
                    alignItems="center"
                    key={idx}
                    xs={item?.farms?.length === 1 ? 12 : 6}
                    mt={"5px"}
                    mb={idx + 1 === item?.farms?.length ? 1 : 0}
                    style={{
                      background: idx % 2 === 1 ? "white" : "ghostwhite",
                      borderStyle: "solid",
                      borderWidth: "1px",
                      borderColor: "gray",
                      borderRadius: "10px",
                    }}
                  >
                    <Typography variant="caption">
                      {option.poultryName} ({option.poultryFullName})
                    </Typography>
                    <Typography variant="caption">
                      {option.poultryMobile}
                    </Typography>
                  </Grid>
                ))
              : "-"}
          </Grid>,
          <VetFarmActions key={`actions-vet-${i}`} vetFarm={item} />,
        ];
      }

      if (selectedTab === 2) {
        // تب کشتارگاه (حالا سومین تب است)
        return [
          ...baseInfo,
          <Grid
            container
            alignItems="baseline"
            xs={12}
            key={i}
            spacing={2}
            mt={1}
            mb={1}
          >
            {item?.killHouses?.length
              ? item?.killHouses.map((option, idx) => (
                  <Grid
                    container
                    direction="column"
                    alignItems="center"
                    key={idx}
                    xs={item?.killHouses?.length === 1 ? 12 : 6}
                    mt={"5px"}
                    mb={idx + 1 === item?.killHouses?.length ? 1 : 0}
                    style={{
                      background: idx % 2 === 1 ? "white" : "ghostwhite",
                      borderStyle: "solid",
                      borderWidth: "1px",
                      borderColor: "gray",
                      borderRadius: "10px",
                    }}
                  >
                    <Typography variant="caption">
                      {option.KillHouseName} ({option.KillHouseUserFullName})
                    </Typography>
                    <Typography variant="caption">
                      {option.KillHouseUserMobile}
                    </Typography>
                  </Grid>
                ))
              : "-"}
          </Grid>,
          <KillHouseActions key={`actions-killhouse-${i}`} vet={item} />,
        ];
      }

      // تب دوم: دامپزشکان بدون فارم
      return [
        ...baseInfo,
        <VetFarmActions key={`actions-vet-no-farm-${i}`} vetFarm={item} />,
      ];
    });

    setTableData(d);
  }, [data, page, perPage, selectedTab]);

  return (
    <Grid container mt={2} justifyContent="center" xs={12}>
      <Grid
        container
        justifyContent="center"
        alignItems="center"
        mb={SPACING.MEDIUM}
        mt={SPACING.SMALL}
        xs={12}
      >
        <Tabs
          scrollButtons="auto"
          variant="scrollable"
          allowScrollButtonsMobile
          value={selectedTab}
          onChange={handleTabChange}
        >
          <Tab label="دامپزشکان فارم" />
          <Tab label="دامپزشکان بدون فارم" />
          <Tab label="دامپزشکان کشتارگاه" />
        </Tabs>
      </Grid>

      <Grid justifyContent="start" container xs={12}>
        <form onSubmit={handleSubmit}>
          <TextField
            id="outlined-basic"
            size="small"
            label="جستجو"
            variant="outlined"
            style={{ width: 250 }}
            onChange={handleTextChange}
            value={textValue}
          />
          <Button type="submit" endIcon={<RiSearchLine />}>
            جستجو
          </Button>
        </form>
      </Grid>

      <ResponsiveTable
        title={
          selectedTab === 0
            ? "مدیریت دامپزشکان فارم"
            : selectedTab === 2
            ? "مدیریت دامپزشکان کشتارگاه"
            : "مدیریت دامپزشکان بدون فارم"
        }
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        columns={
          selectedTab === 0
            ? [
                "ردیف",
                "نام و نام خانوادگی",
                "کدملی",
                "تلفن",
                "استان",
                "شهرستان",
                "فارم ها",
                "عملیات",
              ]
            : selectedTab === 2
            ? [
                "ردیف",
                "نام و نام خانوادگی",
                "کدملی",
                "تلفن",
                "استان",
                "شهرستان",
                "کشتارگاه ها",
                "عملیات",
              ]
            : [
                "ردیف",
                "نام و نام خانوادگی",
                "کدملی",
                "تلفن",
                "استان",
                "شهرستان",
                "عملیات",
              ]
        }
        data={tableData}
      />
    </Grid>
  );
};
