import DownloadIcon from "@mui/icons-material/Download";
import { Box, IconButton, LinearProgress, TextField } from "@mui/material";
import { format } from "date-fns";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
import Table from "../../components/Table";
import {
  downloadBulkCallTranscripts,
  getCallTranscripts,
} from "../../services/clinics.service";
import { useStyles } from "./clinicTranscriptsStyles";
import PageHeader from "../../components/PageHeader";
import CustomBreadcrumbs from "../../components/CustomBreadcrumbs";
import { DesktopDatePicker, LocalizationProvider } from "@mui/x-date-pickers";


const CallListTable = () => {
  const classes = useStyles();
  const ref = useRef(null);

  const [loading, setLoading] = useState(false);

  const [data, setData] = useState([]);

  // get data
  const getTranscrips = async (filters) => {
    try {
      const params = { ...filters };
      const resp = await getCallTranscripts(params);
      setData(resp?.data?.data?.data);
      return {
        data: resp?.data?.data?.data,
        rowCount: resp?.data?.data?.total || 0,
      };
    } catch (error) {
      console.log(error);
      return {
        data: [],
        rowCount: 0,
      };
    }
  };

  const handleBulkDownload = async () => {
    try {
      setLoading(true);
      const keys = data.map((item) => item.id);
      const downloadResponse = await downloadBulkCallTranscripts(keys);
      // const blob = new Blob([downloadResponse?.data], { type: "application/zip" });
      const url = window.URL.createObjectURL(downloadResponse?.data);
      const a = document.createElement("a");
      a.href = url;
      a.download = "transcripts.zip";
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  const columns = useMemo(() => [
    {
      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,
    },
    {
      id: "call_duration",
      size: 200,
      accessorKey: "call_duration",
      header: "Call Duration",
      Cell: (props) => {
        const totalSeconds = parseInt(props.row.original.call_duration);
        const minutes = Math.floor(totalSeconds / 60);
        const seconds = totalSeconds % 60;
        return (
          <span>
            {minutes > 0 ? `${minutes} min ` : ""}
            {seconds > 0 || minutes === 0 ? `${seconds} sec` : ""}
          </span>
        );
      },
      enableSorting: false,
      enableColumnFilter: false,
    },
    {
      id: "call_received_time",
      size: 200,
      accessorKey: "call_received_time",
      header: "Call Received Time",
      Cell: (props) => {
        const date = new Date(props.row.original.call_received_time);
        const formattedDate = format(date, "MMM d, yyyy h:mm a");
        return <span>{formattedDate}</span>;
      },
      enableSorting: false,
      enableColumnFilter: false,
    },
    {
      id: "patient_number",
      size: 200,
      accessorKey: "patient_number",
      header: "Patient Number",
      Cell: (props) => {
        return <span>{props.row.original.patient_number}</span>;
      },
      enableSorting: false,
      enableColumnFilter: false,
    },
    {
      size: 20,
      accessorKey: "download",
      header: "",
      enableColumnFilter: false,
      enableSorting: false,
      Cell: (props) => {
        const { row } = props;
        const handleDownload = async () => {
          const a = document.createElement("a");
          a.href = row.original.transcript_key_id;
          a.download = "transcript.txt";
          document.body.appendChild(a);
          a.click();
          a.remove();
        };
        return (
          <IconButton onClick={handleDownload}>
            <DownloadIcon />
          </IconButton>
        );
      },
    },
    // {
    //   id: "patient_name",
    //   size: 150,
    //   accessorKey: "patient_name",
    //   header: "Patient Name",
    //   Cell: (props) => {
    //     return <span>{props.row.original.patient_name}</span>;
    //   },
    //   enableColumnFilter: false,
    // },
  ]);

  const breadcrumbs = [
    {
      label: "Dashboard",
      path: "/",
    },
    {
      label: "Call Transcripts",
      path: "/transcripts",
    },
  ];


  return (
    <Box>
      <PageHeader
        pageTitle="Call Transcripts"
        addButtonIcon={<DownloadIcon />}
        addButtonTitle="Bulk Download"
        onAddButtonClick={handleBulkDownload}
      />
      <CustomBreadcrumbs breadcrumbs={breadcrumbs} />
      <Box className={classes.tableMainDiv}>
        <Box className={classes.table}>
          {loading && <LinearProgress />}
          <Table
            tableRef={ref}
            options={{
              enableRowSelection: false,
              showTopBar: true,
              showFilters: true,
            }}
            topToolbarProps={{
              
            }}
            renderTopToolbar={() => {
              return (
                <Box>
                  <TextField
                    variant="outlined"
                    value={"123"}
                    onChange={(e) => setSearchText(e.target.value)}
                    placeholder="Search..."
                  />
                </Box>
              );
            }}
            showDateFilters
            columns={columns}
            getData={getTranscrips}
            searchText="Transcripts"
          />
        </Box>
      </Box>
    </Box>
  );
};

export default CallListTable;
