import {
  Button,
  FormControlLabel,
  IconButton,
  Switch,
  Tooltip,
  Typography,
} from "@mui/material";
import React from "react";
import { useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import NavigateNextIcon from "@mui/icons-material/NavigateNext";
import { useDispatch, useSelector } from "react-redux";
import { useState } from "react";
import EditIcon from "@mui/icons-material/Edit";
import InfoIcon from "@mui/icons-material/Info";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { provinceGetUserByKey } from "../../../province/services/province-get-user-by-key";
import { InspectorEditUserProfile } from "../../../inspector/components/inspector-edit-user-profile/InspectorEditUserProfile";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { inspectorChangeUserState } from "../../../inspector/services/inspector-change-user-state";
import { CitySubmitTenantForm } from "../city-submit-tenant-form/CitySubmitTenantForm";
import { InspectorEditAviculture } from "../../../inspector/components/inspector-edit-aviculture/InspectorEditAviculture";
import { format } from "date-fns-jalali";

// import { inspectorUpdateUserProfile } from "../../services/inspector-update-user-profile";

export const CityUserFileInfo = () => {
  const { userid } = useParams();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [dataTable, setDataTable] = useState([]);
  const { provinceUserInfo } = useSelector((state) => state.provinceSlice);

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(provinceGetUserByKey(userid)).then(() => {
      dispatch(LOADING_END());
    });
  }, []);

  useEffect(() => {
    const userRoles = provinceUserInfo?.profile.role?.map((item, i) => {
      let name = "";
      switch (item) {
        case "ProvinceOperator":
          name = "اپراتور تخصیص استان";
          break;
        case "CityOperator":
          name = "اپراتور شهرستان";
          break;
        case "KillHouseVet":
          name = "دامپزشک کشتارگاه";
          break;
        case "VetFarm":
          name = "دامپزشک";
          break;
        case "Poultry":
          name = "مرغدار";
          break;
        case "KillHouse":
          name = "کشتارگاه";
          break;
        case "Vet":
          name = "دامپزشک";
          break;
        case "ProvinceInspector":
          name = "بازرس استان";
          break;
        case "ProvinceFinancial":
          name = "اپراتور مالی";
          break;
        case "Driver":
          name = "راننده";
          break;
        case "Admin":
          name = "ادمین";
          break;
        default:
          name = "کاربر پایه";
          break;
      }
      return <div key={i}>{name}</div>;
    });
    const userProfilePic =
      provinceUserInfo?.profile?.image > 5 ? (
        <a href={provinceUserInfo?.profile.image}>
          <img
            width="80"
            height="80"
            alt="img"
            src={provinceUserInfo?.profile.image}
          />
        </a>
      ) : (
        "موجود نیست"
      );
    const b = [
      [
        provinceUserInfo?.profile?.fullname
          ? provinceUserInfo?.profile?.fullname
          : provinceUserInfo?.profile?.firstName +
            " " +
            provinceUserInfo?.profile?.lastName,
        userRoles,
        provinceUserInfo?.profile?.mobile,
        provinceUserInfo?.profile?.birthday
          ? format(new Date(provinceUserInfo?.profile?.birthday), "yyyy/MM/dd")
          : "نامشخص",
        provinceUserInfo?.profile?.city,
        <Typography variant="caption" key="password">
          {provinceUserInfo?.profile?.password}
        </Typography>,
        userProfilePic,
        <IconButton
          key={provinceUserInfo}
          aria-label="delete"
          color="primary"
          className="avicultureActiveRequestsBtn"
          onClick={() => {
            // dispatch(inspectorUpdateUserProfile());
            dispatch(
              DRAWER({
                title: "ویرایش پروفایل کاربر",
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: (
                  <InspectorEditUserProfile
                    id={provinceUserInfo?.profile?.key}
                    birthday={provinceUserInfo?.profile?.birthday}
                    nationalCode={provinceUserInfo?.profile?.nationalCode}
                    nationalId={provinceUserInfo?.profile?.nationalId}
                    firstName={provinceUserInfo?.profile?.firstName}
                    lastName={provinceUserInfo?.profile?.lastName}
                    password={provinceUserInfo?.profile?.password}
                    phone={provinceUserInfo?.profile?.mobile}
                  />
                ),
              })
            );
          }}
        >
          <EditIcon />
        </IconButton>,
      ],
    ];

    setDataTable(b);
  }, [provinceUserInfo]);

  return (
    <>
      <Grid container alignItems="center" mt={SPACING.SMALL}>
        <IconButton
          aria-label="delete"
          color="primary"
          onClick={() => navigate(-1)}
        >
          <NavigateNextIcon />
          <Typography>بازگشت</Typography>
        </IconButton>
      </Grid>

      <Grid
        container
        xs={12}
        alignItems={"start"}
        gap={SPACING.SMALL}
        direction={"column"}
      >
        <Grid
          width="100%"
          container
          alignItems="center"
          justifyContent="space-between"
        >
          <Grid width="100%" className="second">
            <SimpleTable
              name="اطلاعات پایه کاربر"
              columns={[
                "نام کامل",
                "نوع کاربری",
                "شمار تلفن",
                "تاریخ تولد",
                "شهر",
                "کلمه عبور",
                "تصویر پروفایل",
                "ویرایش",
              ]}
              data={dataTable}
            />

            {provinceUserInfo?.rolesData?.map((item, i) => {
              if (Object.keys(item).includes("Poultry")) {
                return (
                  <>
                    <SimpleTable
                      key={i}
                      name="اطلاعات مرغدار"
                      columns={[
                        "نام فارم",
                        "آدرس",
                        "استان",
                        "شهر",
                        "کد پستی",
                        "موبایل",
                        "شناسه یکتا",
                        "کد اقتصادی",
                        "کد اپیدمیولوژیک",
                        "تعداد سالن",
                        "ویرایش",
                        "وضعیت",
                      ]}
                      data={[
                        [
                          item.Poultry?.unitName,
                          item.Poultry.address?.address,
                          item.Poultry.address?.province?.name,
                          item.Poultry.address?.city?.name,
                          Number(item.Poultry.address?.postalCode),
                          item.Poultry.address?.phone,
                          item.Poultry.breedingUniqueId,
                          item.Poultry.economicCode,
                          item.Poultry.epidemiologicalCode,
                          item.Poultry.numberOfHalls,
                          <Tooltip
                            key={i}
                            title={"ویرایش کاربر"}
                            placement="bottom-start"
                          >
                            <IconButton
                              aria-label="delete"
                              color="primary"
                              className="avicultureActiveRequestsBtn"
                              onClick={() => {
                                dispatch(
                                  DRAWER({
                                    title: "ویرایش اطلاعات مرغدار",
                                    right: !(window.innerWidth <= 600),
                                    bottom: window.innerWidth <= 600,
                                    content: (
                                      <InspectorEditAviculture
                                        farmName={item.Poultry?.unitName}
                                        id={provinceUserInfo?.profile.key}
                                        type="Poultry"
                                        uniqueId={
                                          item.Poultry?.breedingUniqueId
                                        }
                                        address={item.Poultry.address?.address}
                                        poultry={item.Poultry?.key}
                                        halls={item.Poultry.numberOfHalls}
                                        postal={Number(
                                          item.Poultry.address?.postalCode
                                        )}
                                        accountHolder={
                                          item.Poultry.userBankInfo
                                            ?.nameOfBankUser
                                        }
                                        card={item.Poultry.userBankInfo?.card}
                                        shaba={item.Poultry.userBankInfo?.shaba}
                                        account={
                                          item.Poultry.userBankInfo?.account
                                        }
                                        name_of_bank_user={
                                          item.Poultry.userBankInfo?.bankName
                                        }
                                      />
                                    ),
                                  })
                                );
                              }}
                            >
                              <EditIcon />
                            </IconButton>
                          </Tooltip>,
                          <Tooltip
                            key={i}
                            title={
                              item.Poultry.trash === true
                                ? "فعالسازی کاربر"
                                : "غیر فعال کردن کاربر"
                            }
                            placement="bottom-start"
                          >
                            <FormControlLabel
                              label={
                                item.Poultry.trash === true
                                  ? "غیرفعال"
                                  : " فعال"
                              }
                              control={
                                <Switch
                                  checked={!item.Poultry.trash}
                                  onClick={() => {
                                    dispatch(LOADING_START());
                                    dispatch(
                                      inspectorChangeUserState({
                                        type:
                                          item.Poultry.trash === true
                                            ? "Activate"
                                            : "Deactivate",
                                        role_data_key: item.Poultry.key,
                                        role: "Poultry",
                                      })
                                    ).then((r) => {
                                      dispatch(LOADING_END());
                                      window.location.reload(false);
                                    });
                                  }}
                                />
                              }
                            />
                          </Tooltip>,
                        ],
                      ]}
                    />

                    <SimpleTable
                      key={i}
                      name="اطلاعات بانکی مرغدار"
                      expandable
                      columns={[
                        "نام صاحب حساب",
                        "نام بانک",
                        "شماره حساب",
                        "شماره کارت",
                        "شماره شبا",
                      ]}
                      data={[
                        [
                          item.Poultry.userBankInfo?.nameOfBankUser,
                          item.Poultry.userBankInfo?.bankName,
                          Number(item.Poultry.userBankInfo?.account),
                          Number(item.Poultry.userBankInfo?.card),
                          item.Poultry.userBankInfo?.shaba,
                        ],
                      ]}
                    />
                    {Object.keys(item.Poultry?.poultryTenant).length > 0 ? (
                      <SimpleTable
                        key={i}
                        name="اطلاعات مستاجر مرغدار"
                        expandable
                        columns={[
                          "شناسه یکتا",
                          "نام کامل",
                          "تلفن همراه",
                          "کد ملی",
                        ]}
                        data={[
                          [
                            item.Poultry.poultryTenant?.breedingUniqueId,
                            item.Poultry.poultryTenant?.fullName,
                            item.Poultry.poultryTenant?.mobile,
                            item.Poultry.poultryTenant?.nationalId,
                          ],
                        ]}
                      />
                    ) : (
                      !item.Poultry.poultryOwner.length > 0 && (
                        <Grid
                          display="flex"
                          mt={SPACING.MEDIUM}
                          gap={SPACING.SMALL}
                          alignItems="center"
                          mb={SPACING.MEDIUM}
                        >
                          <Grid display="flex" gap={SPACING.TINY}>
                            <InfoIcon color="primary" />
                            <Typography>مرغدار مستاجر ندارد</Typography>
                          </Grid>
                          <Button
                            variant="outlined"
                            onClick={() => {
                              dispatch(
                                DRAWER({
                                  right: !(window.innerWidth <= 600),
                                  bottom: window.innerWidth <= 600,
                                  title: "ایجاد مستاجر جدید",
                                  content: (
                                    <CitySubmitTenantForm
                                      id={item.Poultry.key}
                                      userid={userid}
                                    />
                                  ),
                                })
                              );
                            }}
                          >
                            افزودن مستاجر
                          </Button>
                        </Grid>
                      )
                    )}
                  </>
                );
              }
              return null;
            })}
          </Grid>
        </Grid>
      </Grid>
    </>
  );
};
