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 {
  Box,
  Chip,
  Tab,
  Tabs,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Button,
  Typography,
  IconButton,
} from "@mui/material";
import { differenceInDays, format } from "date-fns";
import { LoadingButton } from "@mui/lab";
import FileDownloadIcon from "@mui/icons-material/FileDownload";
import CloseIcon from "@mui/icons-material/Close";

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

const ClinicsList = () => {
  const theme = useTheme();
  const ref = useRef(null);
  const classes = useStyles();
  const params = useLocation();
  const queryParams = new URLSearchParams(params.search);
  const [type, setType] = useState(
    queryParams.get("tab") ?? CLINIC_TYPE.UNREGISTERED
  );
  const [isDownloading, setIsDownloading] = useState(false);
  const [totalActive, setTotalActive] = useState(0);
  const [totalInactive, setTotalInactive] = useState(0);

  // State for freeze clinic confirmation dialog
  const [freezeDialogOpen, setFreezeDialogOpen] = useState(false);
  const [clinicToFreeze, setClinicToFreeze] = useState(null);

  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: 100,
          header: "Sr. No.",
          Cell: (props) => {
            const tableState = props?.table?.getState();
            const serialNumber = (
              props?.row?.index +
              1 +
              tableState?.pagination?.pageIndex *
                tableState?.pagination?.pageSize
            )
              ?.toString()
              ?.padStart(1, "0");
            return <span>{serialNumber}</span>;
          },
          enableSorting: false,
        },
        // .................company name column..................
        {
          enableColumnFilter: false,
          enableSorting: true,
          size: "220px",
          accessorKey: "name",
          header: "Clinic Name",
          Cell: ({ row }) => (
            <>
              <div className={classes.companyNameTableColumn}>
                {/* <img
                  className={classes.companyNameLogo}
                  src="https://dev-ai-appointment.s3.ap-southeast-2.amazonaws.com/common/clinic_logo.jpg"
                  alt="logo"
                /> */}
                <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: false,
          accessorKey: "status",
          header: "Status",
          size: 100,
          enableColumnFilter: false,
          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.PAYMENT_DUE ? (
                    "Payment Due"
                  ) : 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.PAYMENT_DUE.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.PAYMENT_DUE.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: 100,
          header: "Sr. No.",
          Cell: (props) => {
            const tableState = props?.table?.getState();
            const serialNumber = (
              props?.row?.index +
              1 +
              tableState?.pagination?.pageIndex *
                tableState?.pagination?.pageSize
            )
              ?.toString()
              ?.padStart(1, "0");
            return <span>{serialNumber}</span>;
          },
          enableSorting: false,
        },
        // .................company name column..................
        {
          enableSorting: true,
          size: 200,
          accessorKey: "name",
          header: "Clinic Name",
          Cell: ({ row }) => (
            <>
              <div className={classes.companyNameTableColumn}>
                {/* <img
                  className={classes.companyNameLogo}
                  src="https://dev-ai-appointment.s3.ap-southeast-2.amazonaws.com/common/clinic_logo.jpg"
                  alt="logo"
                /> */}

                <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: 150,
          accessorKey: "update_time",
          header: "Approved Since",
          Cell: ({ row }) => {
            const approvedAtDate = new Date(row?.original?.update_time);
            const today = new Date();
            const daysDiff = differenceInDays(today, approvedAtDate);

            return (
              <>
                <div>
                  {daysDiff === 0
                    ? "Today"
                    : daysDiff === 1
                    ? "Yesterday"
                    : `${daysDiff} days`}
                </div>
              </>
            );
          },
        },
        {
          enableSorting: false,
          size: 100,
          header: "Actions",
          Cell: ({ row }) => {
            return (
              <div className={classes.actions}>
                <Button
                  variant="contained"
                  color="primary"
                  onClick={() => openFreezeConfirmation(row)}
                >
                  {row.original.status === CLINIC_STATUS.INACTIVE
                    ? "Unfreeze"
                    : "Freeze"}
                </Button>
              </div>
            );
          },
        },
      ].filter(Boolean),
    [type]
  );

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

  const getData = async (filters, unregistered = true) => {
    let params = {
      ...filters,
      type,
    };
    const resp = await getClinics(params);
    setTotalActive(resp?.data?.data?.data?.totalRegisteredClinics);
    setTotalInactive(resp?.data?.data?.data?.totalRejectedClinics);
    return {
      data: resp?.data?.data?.data?.clinics,
      rowCount: unregistered
        ? resp?.data?.data?.data?.totalRejectedClinics
        : resp?.data?.data?.data?.totalRegisteredClinics,
    };
  };

  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);
    // }
  };

  // Open freeze confirmation dialog
  const openFreezeConfirmation = (row) => {
    setClinicToFreeze(row.original);
    setFreezeDialogOpen(true);
  };

  // Handle freeze/unfreeze clinic after confirmation
  const handleFreezeClinic = async () => {
    try {
      // Determine if we're freezing or unfreezing based on current status
      const isCurrentlyFrozen =
        clinicToFreeze.status === CLINIC_STATUS.INACTIVE;
      const newStatus = isCurrentlyFrozen ? "active" : CLINIC_STATUS.INACTIVE;

      const payload = {
        clinic_id: clinicToFreeze.id,
        status: newStatus,
      };

      const resp = await updateClinicStatus(payload);

      // Show appropriate success message
      const successMessage = isCurrentlyFrozen
        ? "Clinic unfrozen successfully"
        : "Clinic frozen successfully";
      pushNotification(successMessage, NOTIFICATION.SUCCESS);

      // Refresh the table
      if (ref.current) {
        ref.current.reFetchData();
      }
    } catch (error) {
      // Show appropriate error message
      const isCurrentlyFrozen =
        clinicToFreeze.status === CLINIC_STATUS.INACTIVE;
      const errorMessage = isCurrentlyFrozen
        ? "Failed to unfreeze clinic"
        : "Failed to freeze clinic";

      console.error(
        `Error ${isCurrentlyFrozen ? "unfreezing" : "freezing"} clinic:`,
        error
      );
      pushNotification(errorMessage, NOTIFICATION.ERROR);
    }

    // Close the dialog
    setFreezeDialogOpen(false);
    setClinicToFreeze(null);
  };

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

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

  return (
    <>
      <Box>
        <PageHeader
          pageTitle="Clinics"
          hideAddButton
          addButtonIcon={<FileDownloadIcon />}
          extraComponent={
            <Box className={classes.tabsBox}>
              <Tabs value={type} onChange={handleTabsChange}>
                <Tab
                  value={CLINIC_TYPE.UNREGISTERED}
                  label={`Unregistered (${totalInactive})`}
                />
                <Tab
                  value={CLINIC_TYPE.REGISTERED}
                  label={`Registered (${totalActive})`}
                />
                {/* <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={(filters) => getData(filters, true)} // true for unregistered
                options={{
                  enableRowSelection: false,
                  showTopBar: false,
                  showFilters: true,
                }}
                searchText="Clinics"
                showSearchBox={true}
                ref={ref}
              />
            )}
            {type === CLINIC_TYPE.REGISTERED && (
              <Table
                hideTopToolbar
                columns={columnsRegistered}
                getData={(filters) => getData(filters, false)} // false for registered
                options={{ enableRowSelection: true, showTopBar: false }}
                showSearchBox={true}
                ref={ref}
                showAction={true}
                searchText="Clinics"
              />
            )}
          </Box>
        </Box>
      </Box>

      {/* Freeze Clinic Confirmation Dialog */}
      <Dialog
        open={freezeDialogOpen}
        onClose={() => setFreezeDialogOpen(false)}
        maxWidth="xs"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: "12px",
            overflow: "hidden",
          },
        }}
      >
        <DialogTitle
          sx={{
            padding: "16px 24px",
            backgroundColor: (theme) => theme.palette.error.main,
            color: "white",
            fontWeight: "bold",
            position: "relative",
          }}
        >
          {clinicToFreeze?.status === CLINIC_STATUS.INACTIVE
            ? "Confirm Unfreeze Clinic"
            : "Confirm Freeze Clinic"}
          <IconButton
            aria-label="close"
            onClick={() => setFreezeDialogOpen(false)}
            sx={{
              position: "absolute",
              right: 8,
              top: 8,
              color: "white",
            }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>

        <DialogContent sx={{ padding: "24px 24px 16px", mt: 1 }}>
          <Typography variant="body1">
            {clinicToFreeze?.status === CLINIC_STATUS.INACTIVE
              ? `Are you sure you want to unfreeze ${clinicToFreeze?.name}? This will restore the clinic's access to the system.`
              : `Are you sure you want to freeze ${clinicToFreeze?.name}? This will prevent the clinic from accessing the system until unfrozen.`}
          </Typography>
        </DialogContent>

        <DialogActions
          sx={{
            padding: "16px 24px",
            borderTop: "1px solid",
            borderColor: (theme) => theme.palette.grey[200],
            justifyContent: "space-between",
          }}
        >
          <Button
            onClick={() => setFreezeDialogOpen(false)}
            sx={{
              color: (theme) => theme.palette.grey[700],
              fontWeight: "medium",
            }}
          >
            Cancel
          </Button>
          <Button
            onClick={handleFreezeClinic}
            variant="contained"
            color="error"
            sx={{
              borderRadius: "8px",
              px: 3,
            }}
          >
            {clinicToFreeze?.status === CLINIC_STATUS.INACTIVE
              ? "Unfreeze"
              : "Freeze"}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};

export default ClinicsList;
