import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import moment from "moment";
import { Button, TextField, Tooltip, IconButton, Box } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { RiSearchLine, RiFileExcel2Fill } from "react-icons/ri";
import axios from "axios";
import { AppContext } from "../contexts/AppContext";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../lib/redux/slices/appSlice";
import { Grid } from "../components/grid/Grid";
import { SPACING } from "../data/spacing";
import ResponsiveTable from "../components/responsive-table/ResponsiveTable";
import { BackButton } from "../components/back-button/BackButton";
import { inspectorGetPoultryScienceReport } from "../features/inspector/services/inspector-get-poultry-science-report";
import { InspectionDetailsModal } from "../components/inspection-details-modal/InspectionDetailsModal";
import VisibilityIcon from "@mui/icons-material/Visibility";
import { formatJustDate } from "../utils/formatTime";

const Inspection = () => {
  const dispatch = useDispatch();
  const [textValue, setTextValue] = useState("");
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [data, setData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [page, setPage] = useState(1);

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [openNotif] = useContext(AppContext);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

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

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    try {
      const response = await inspectorGetPoultryScienceReport(page, perPage);
      setData(response.results || []);
      setTotalRows(response.count || 0);
    } catch (error) {
      console.error("Error fetching inspection data:", error);
      setData([]);
      setTotalRows(0);
    }
    dispatch(LOADING_END());
  };

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

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

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

  const handleViewDetails = (item) => {
    dispatch(
      OPEN_MODAL({
        title: "جزئیات",
        size: 1280,
        content: <InspectionDetailsModal item={item} />,
      })
    );
  };

  const getInspectionStatus = (item) => {
    if (item?.state === "pending") {
      return "در انتظار تایید";
    } else if (item?.state === "accepted") {
      return "تایید شده";
    } else if (item?.state === "rejected") {
      return "رد شده";
    }
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        formatJustDate(item?.date) || "-",
        item?.reportId || "-",
        item?.hatching?.poultry?.unitName || "-",
        item?.hatching?.poultry?.breedingUniqueId || "-",
        item?.hatching?.licenceNumber || "-",
        item?.hatching?.poultry?.user?.city?.name || "-",
        formatJustDate(item?.hatching?.date) || "-",
        item?.hatching?.quantity?.toLocaleString() || "-",
        getInspectionStatus(item) || "-",
        <Box key={`details-${i}`} display="flex" justifyContent="center">
          <IconButton
            color="primary"
            onClick={() => handleViewDetails(item)}
            size="small"
          >
            <VisibilityIcon />
          </IconButton>
        </Box>,
      ];
    });
    setTableData(d || []);
  }, [data, page, perPage]);

  useEffect(() => {
    fetchApiData(1);
  }, [selectedDate1, selectedDate2, perPage]);

  return (
    <Box display="flex" justifyContent="center">
      <Grid
        container
        direction="column"
        flexWrap="nowrap"
        xs={12}
        sm={12}
        md={10}
        lg={10}
      >
        <BackButton />

        <Grid
          xs={12}
          container
          alignItems="center"
          gap={SPACING.SMALL}
          justifyContent="flex-start"
          mb={SPACING.SMALL}
          mt={SPACING.SMALL}
        >
          <form onSubmit={handleSubmit}>
            <Grid container alignItems="center" gap={SPACING.SMALL}>
              <Grid style={{ width: "150px" }}>
                <DatePicker
                  label="از تاریخ"
                  id="date"
                  renderInput={(params) => <TextField {...params} />}
                  value={selectedDate1}
                  onChange={(e) => {
                    setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                  }}
                />
              </Grid>
              <Grid style={{ width: "150px" }}>
                <DatePicker
                  label="تا تاریخ"
                  id="date"
                  renderInput={(params) => <TextField {...params} />}
                  value={selectedDate2}
                  onChange={(e) => {
                    setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                  }}
                />
              </Grid>
              <TextField
                autoComplete="off"
                size="small"
                label="جستجو"
                variant="outlined"
                style={{ width: 250 }}
                onChange={handleTextChange}
                value={textValue}
              />
              <Button
                type="submit"
                onClick={handleSubmit}
                endIcon={<RiSearchLine />}
              >
                جستجو
              </Button>
              <Tooltip title="خروجی اکسل">
                <IconButton
                  color="success"
                  onClick={() => {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "فایل اکسل در حال دانلود می باشد، این عملیات ممکن است زمان بر باشد لطفا صبر کنید.",
                      severity: "success",
                    });
                    // TODO: Replace with actual Excel export endpoint
                    const link = `${axios.defaults.baseURL}inspection_excel/?date1=${selectedDate1}&date2=${selectedDate2}&search=filter&value=${textValue}`;
                    window.location.href = link;
                  }}
                >
                  <RiFileExcel2Fill size={32} />
                </IconButton>
              </Tooltip>
            </Grid>
          </form>
        </Grid>

        <ResponsiveTable
          data={tableData}
          columns={[
            "ردیف",
            "تاریخ بازرسی",
            "شناسه بازرسی",
            "نام فارم",
            "شناسه یکتا",
            "شناسه جوجه ریزی",
            "شهرستان",
            "تاریخ جوجه ریزی",
            "تعداد جوجه ریزی",
            "وضعیت بازرسی",
            "مشاهده جزییات",
          ]}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          paginated={true}
          title="بازرسی"
        />
      </Grid>
    </Box>
  );
};

export default Inspection;
