import React, { useState, useMemo, useEffect, useRef } from "react";
import { useTheme } from "@emotion/react";
import { useLocation, useNavigate,Link } from "react-router-dom";
import StoreIcon from '@mui/icons-material/Store';
import DescriptionIcon from '@mui/icons-material/Description';
import { Box, Chip,Tab, Tabs } from '@mui/material';
import { differenceInDays, format } from 'date-fns';
import { LoadingButton } from '@mui/lab';
import FileDownloadIcon from '@mui/icons-material/FileDownload';



import { useStyles } from "./clinicListStyles";
import { CLINIC_STATUS, CLINIC_TYPE, NOT_AVAILABLE_TEXT, PLAN_STATUS_TYPE } from "../../constants";
import { getClinics } from "../../services/clinics.service";
import CustomBreadcrumbs from "../../components/CustomBreadcrumbs";
import Table from "../../components/Table";
import TableSelect from "../../components/TableSelect";
import PageHeader from '../../components/PageHeader';


const ClinicsList = () => {
  const theme = useTheme();
  const ref = useRef(null);
  const classes = useStyles();
  const params = useLocation();
  const navigate = useNavigate();
  const queryParams = new URLSearchParams(params.search);
  const [type, setType] = useState(
    queryParams.get("tab") ?? CLINIC_TYPE.UNREGISTERED
  );
  const showNewPlanAddedModel =
    Boolean(queryParams.get("isPlanCreated")) ?? false;
  const [isDownloading, setIsDownloading] = useState(false);
  const [showModel, setShowModel] = useState(false);
  const [modelType, setModelType] = useState("");
  const [rowActionData, setRowActionData] = useState("");
  const [isEmailSentPopupOpen, setIsEmailSentPopupOpen] = useState(false);
  const emailList = useRef();


  const UNREGISTERED_CLINIC_STATUS_OPTIONS = [
    { id: 1, name: CLINIC_STATUS.NOT_REVIEWED, showName: 'Approval Pending' },
    { id: 2, name: CLINIC_STATUS.APPROVAL_PENDING_DOCUMENT_RESUBMITTED },
    { id: 3, name: CLINIC_STATUS.ON_HOLD, showName: 'On Hold' },
    { id: 4, name: CLINIC_STATUS.REJECTED, showName: 'Rejected' },
  ];

  const columnsUnregistered = useMemo(
    () =>
      [
        // ..............sro number column......................
        {
          size: 50,
          isBold: true,
          header: "Sr. No.",
          Cell: (props) => {
            const tableState = props?.table?.getState();
            const serialNumber = (
              props?.row?.index +
              1 +
              tableState?.pagination?.pageIndex *
                tableState?.pagination?.pageSize
            )
              ?.toString()
              ?.padStart(2, "0");
            return <span>{serialNumber}</span>;
          },
          enableSorting: false,
        },
        // .................company name column..................
        {
          enableColumnFilter: false,
          enableSorting: true,
          size: "260px",
          accessorKey: "name",
          header: "Clinic Name",
          Cell: ({ row }) => (
            <>
              <div className={classes.companyNameTableColumn}>
                {row?.original?.logo ? (
                  <img alt="logo" className={classes.companyNameLogo} src={row?.original?.logo}/>
                ) : (
                  <StoreIcon />
                )}
                {/* <img
                  className={classes.companyNameLogo}
                  src={
                    row?.original?.logo
                      ? row?.original?.logo
                      : companyDefaultIcon
                  }
                /> */}
                <div className={classes.companyName}>
                  <Link
                    to={{
                      pathname: `/clinics/${row?.original?.id}`,
                      search: `?tab=${type}`,
                    }}
                    className={classes.companyNameLink}
                  >
                    <>{row?.original.name}</>
                  </Link>

                  <div className={classes.companyWebsiteLabel}>
                    {row.original.website}
                  </div>
                </div>
              </div>
            </>
          ),
        },
        // .................req. raised on  column..................
        {
          enableColumnFilter: false,
          enableSorting: true,
          size: 100,
          accessorKey: "update_time",
          header: "Req.Raised On",
          Cell: ({ row }) => (
            <>
              <div>
                {row?.original?.update_time
                  ? format(
                      new Date(row.original.update_time),
                      "dd MMM yyyy"
                    )
                  : NOT_AVAILABLE_TEXT}
              </div>
            </>
          ),
        },
        // .................send email column..................
        {
          enableColumnFilter: false,
          enableSorting: true,
          accessorKey: "lastEmailSent",
          size: 190,
          header: "Send Mail",
          Cell: ({ row }) => (
            <>
              {(row.original.status === CLINIC_STATUS.REJECTED ||
                row.original.status === CLINIC_STATUS.ON_HOLD) && (
                <div>
                  <Link
                    onClick={() => handleEmailSent(row)}
                    className={classes.sendEmailStatus}
                  >
                    <u>
                      {row.original.status === CLINIC_STATUS.ON_HOLD &&
                        "Resend On Hold Mail"}
                      {row.original.status === CLINIC_STATUS.REJECTED &&
                        "Resend Rejection Mail"}
                    </u>
                  </Link>
                  <div className={classes.sendEmailLastSentMailDate}>
                    Last Sent On:
                    {format(
                      new Date(row?.original?.lastEmailSent),
                      "dd MMM yyyy"
                    )}
                  </div>
                </div>
              )}
            </>
          ),
        },
        // .................location column..................
        {
          size: 100,
          enableColumnFilter: false,
          enableSorting: true,
          accessorKey: "city",
          header: "Location",
          Cell: ({ row }) => (
            <>
              <div>{row.original.city}</div>
            </>
          ),
        },
        // .................Company status column..................
        {
          enableSorting: true,
          accessorKey: "status",
          header: "Status",
          size: 100,
          Filter: ({ header }) => (
            <TableSelect
              name="Status"
              header={header}
              options={UNREGISTERED_CLINIC_STATUS_OPTIONS}
            />
          ),
          accessorFn: ({ status }) => (
            <>
              <Chip
                className={classes.chipClass}
                label={
                  status === CLINIC_STATUS.UNDER_REVIEW.toLowerCase() ? (
                    "Under Review"
                  ) : status === CLINIC_STATUS.NOT_REVIEWED ? (
                    "Approval Pending"
                  ) : status ===
                    CLINIC_STATUS.APPROVAL_PENDING_DOCUMENT_RESUBMITTED ? (
                    <div>
                      Approval Pending
                      <div className={classes.statusColor}>
                        Document Resubmitted
                      </div>
                    </div>
                  ) : status === CLINIC_STATUS.REJECTED.toLowerCase() ? (
                    "Rejected"
                  ) : (
                    ""
                  )
                }
                style={{
                  backgroundColor:
                    status === CLINIC_STATUS.ON_HOLD.toLowerCase()
                      ? theme.palette.orange.light
                      : status === CLINIC_STATUS.NOT_REVIEWED.toLowerCase() ||
                        status === CLINIC_STATUS.REJECTED.toLowerCase()
                      ? theme.palette.primary.highlight
                      : status ===
                        CLINIC_STATUS.APPROVAL_PENDING_DOCUMENT_RESUBMITTED
                      ? theme.palette.primary.highlight
                      : theme.palette.blue.light,
                  color:
                    status === CLINIC_STATUS.ON_HOLD.toLowerCase()
                      ? theme.palette.orange.main
                      : status === CLINIC_STATUS.NOT_REVIEWED.toLowerCase() ||
                        status === CLINIC_STATUS.REJECTED.toLowerCase()
                      ? theme.palette.primary.main
                      : status ===
                        CLINIC_STATUS.APPROVAL_PENDING_DOCUMENT_RESUBMITTED
                      ? theme.palette.pink.main // Set to yellow for resubmitted
                      : theme.palette.blue.main,
                }}
              />
            </>
          ),
        },
      ].filter(Boolean),
    [type]
  );

  const columnsRegistered = useMemo(
    () =>
      [
        // ..............sro number column......................
        {
          size: 60,
          header: "Sr. No.",
          Cell: (props) => {
            const tableState = props?.table?.getState();
            const serialNumber = (
              props?.row?.index +
              1 +
              tableState?.pagination?.pageIndex *
                tableState?.pagination?.pageSize
            )
              ?.toString()
              ?.padStart(2, "0");
            return <span>{serialNumber}</span>;
          },
          enableSorting: false,
        },
        // .................company name column..................
        {
          enableSorting: true,
          size: 260,
          accessorKey: "name",
          header: "Clinic Name",
          Cell: ({ row }) => (
            <>
              <div className={classes.companyNameTableColumn}>
                {row?.original?.logo ? (
                  <img className={classes.companyNameLogo} src={row?.original?.logo} alt="logo" />
                ) : (
                  <StoreIcon />
                )}
                {/* <img
                  className={classes.companyNameLogo}
                  src={
                    row?.original?.logo
                      ? row?.original?.logo
                      : companyDefaultIcon
                  }
                /> */}

                <div className={classes.companyName}>
                  <Link
                    to={{
                      pathname: `/clinics/${row?.original?.id}`,
                      search: `?tab=${type}`,
                    }}
                    className={classes.companyNameLink}
                  >
                    <>{row?.original.name}</>
                  </Link>
                  <div className={classes.companyWebsiteLabel}>
                    {row.original.website}
                  </div>
                </div>
              </div>
            </>
          ),
        },
        // ......................approve at column...............
        {
          enableSorting: true,
          size: 100,
          accessorKey: "approvedAt",
          header: "Approved Since",
          Cell: ({ row }) => {
            const approvedAtDate = new Date(row?.original?.approvedAt);
            const today = new Date();
            const daysDiff = differenceInDays(today, approvedAtDate);

            return (
              <>
                <div>
                  {daysDiff === 0
                    ? "Today"
                    : daysDiff === 1
                    ? "Yesterday"
                    : `${daysDiff} days`}
                </div>
              </>
            );
          },
        },
        // ........................... sent email column.............................
        // {
        //   enableSorting: true,
        //   accessorKey: 'hasActiveCustomPlan',
        //   minSize: 250,
        //   header: 'Sent Mail',
        //   Cell: ({ row }) => (
        //     <>
        //       {row?.original?.plans?.[0]?.status ===
        //         PLAN_STATUS_TYPE.ACTIVATED && (
        //         <div>
        //           <Link
        //             onClick={() => handleRegisterEmailSent(row)}
        //             className={classes.sendEmailStatus}
        //           >
        //             <u>Resend Subscription Mail</u>
        //           </Link>
        //           <div className={classes.sendEmailLastSentMailDate}>
        //             Last Sent On:{' '}
        //             {format(
        //               new Date(row?.original?.lastCustomPlanEmailSent),
        //               'dd MMM yyyy'
        //             )}
        //           </div>
        //         </div>
        //       )}
        //     </>
        //   ),
        // },

        // ................add plan column..............................
        // {
        //   enableSorting: true,
        //   isBold: true,
        //   size: 120,
        //   accessorKey: 'hasActiveCustomPlan',
        //   header: 'Custom Plan',
        //   Cell: ({ row }) => (
        //     <>
        //       {row?.original?.plans?.[0]?.status ===
        //       PLAN_STATUS_TYPE.ACTIVATED ? (
        //         <Box>
        //           <div className={classes.planAddedText}>
        //             Plan Added <VerifiedIcon className={classes.verifyIcon} />
        //           </div>
        //         </Box>
        //       ) : (
        //         <Tooltip>
        //           <Link
        //             to={{
        //               pathname: `/plans/${row.original.id}/custom-create`,
        //               search: `?tab=${type}`,
        //             }}
        //             className={classes.addDiscountCodeLink}
        //           >
        //             <u>ADD PLAN</u>
        //           </Link>
        //         </Tooltip>
        //       )}
        //     </>
        //   ),
        // },
      ].filter(Boolean),
    [type]
  );

  const handleTabsChange = (event, newValue) => {
    setType(newValue);
  };

  const getData = async (filters) => {
    let params = {
      ...filters,
      type,
    };
    const resp = await getClinics(params);
    console.log(resp)
    return {
      data: resp?.data?.data?.data?.clinics,
      rowCount: resp?.data?.data?.total,
    };
  };

  const handleExport = async () => {
    // const selectedRowData = ref.current.getSelectedRowData();
    // const idArray = selectedRowData.map((item) => item.id);
    // setIsDownloading(true);
    // try {
    //   const response = await getCompaniesExport(type, idArray);
    //   const columnOrder = EXCEL_COLUMN_ORDERS[type.toUpperCase()];
    //   exportToExcel(
    //     response?.data?.data?.records,
    //     columnOrder,
    //     type,
    //     COMPANY_TYPE[type.toUpperCase()].toLowerCase(),
    //     type
    //   );
    // } catch (e) {
    //   pushNotification(e.message, NOTIFICATION.ERROR);
    // } finally {
    //   setIsDownloading(false);
    // }
  };

  const handleRequestSentClose = () => {
    // setIsEmailSentPopupOpen(false);
  };

  const breadcrumbs = [
    {
      label: "Dashboard",
      path: "/",
    },
    {
      label: "Clinic List",
      path: "/clinics",
      query: { tab: queryParams.get('tab') || 'UNREGISTERED' }
    },
  ];

  useEffect(() => {
    ref.current.resetPage();
    ref.current.reFetchData();
  }, [type]);

  return (
    <>
      <Box>
      <PageHeader
          pageTitle="Clinic List"
          hideAddButton
          addButtonIcon={
            <FileDownloadIcon />
          }
          extraComponent={
            <Box className={classes.tabsBox}>
              <Tabs value={type} onChange={handleTabsChange}>
                <Tab value={CLINIC_TYPE.UNREGISTERED} label="Unregistered (2)" />
                <Tab value={CLINIC_TYPE.REGISTERED} label="Registered (2)" />
                {/* <Tab value={COMPANY_TYPE.SUBSCRIBED} label="Subscribers" /> */}
              </Tabs>
            </Box>
          }
          secondaryButton={
            <LoadingButton
              className={classes.secondaryButton}
              color="primary"
              variant="outlined"
              loading={isDownloading}
              startIcon={
                <FileDownloadIcon />
              }
              // onClick={handleExport}
            >
              Download Excel
            </LoadingButton>
          }
        />
        <CustomBreadcrumbs breadcrumbs={breadcrumbs} />

        <Box className={classes.tableMainDiv}>
          <Box>
            {type === CLINIC_TYPE.UNREGISTERED && (
              <Table
                hideTopToolbar
                columns={columnsUnregistered}
                getData={getData}
                options={{
                  enableRowSelection: true,
                  showTopBar: false,
                  showFilters: true,
                }}
                searchText="Clinics"
                showSearchBox={true}
                ref={ref}
              />
            )}
            {type === CLINIC_TYPE.REGISTERED && (
              <Table
                hideTopToolbar
                columns={columnsRegistered}
                getData={getData}
                options={{ enableRowSelection: true, showTopBar: false }}
                showSearchBox={true}
                ref={ref}
                showAction={true}
                searchText="Clinics"
                actions={[
                  {
                    onClick: (row) =>
                      handleModelOpen(row, "transactionHistory"),
                    text: "Freeze Clinic",
                    icon: (
                      <DescriptionIcon />
                      // <img
                      //   src={TransactionHistoryIcon}
                      //   className={classes.tableActionIcons}
                      //   alt="transaction history"
                      // />
                    ),
                  },
                ]}
              />
            )}
          </Box>
        </Box>
      </Box>
    </>
  );
};

export default ClinicsList;
