/* eslint-disable -- temporary disable for development/testing purposes */
'use client';

import * as React from 'react';
import {  useState,} from 'react';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Checkbox from '@mui/material/Checkbox';
import Divider from '@mui/material/Divider';
import Stack from '@mui/material/Stack';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableHead from '@mui/material/TableHead';
import TablePagination from '@mui/material/TablePagination';
import TableRow from '@mui/material/TableRow';
import Typography from '@mui/material/Typography';
import { Snackbar, Alert } from '@mui/material';

import { useSelection } from '@/hooks/use-selection';
// import { useRouter } from 'next/navigation';
import { RowActions } from './row-actions'; // adjust path if needed
import { BroadcastModal } from './broadcast-modal'; // Adjust path if necessary
import { AssignModal } from './assign-modal'; // Adjust path if necessary

function noop(): void {
  // do nothing
}

export interface Customer {
  id: string;
  avatar: string;
  name: string;
  email: string;
  city: string;
  state: string;
  address: string;
  mobile_number: string;
  createdAt: Date;
  company_name: string;
  user_status: string;
  z_code: string;
  total_complete_appointments: string;
  dob: string;
  total_pending_appointments: string;
  category:string | null;
  lat :string|null;
  lng :string|null;
  gender: string | null;



  
}
interface AssignParams {
  userId: string;
  category: string | null;
  patientLat: string | null;
  patientLng: string | null;
  patientName: string | null;
  patientAddress: string | null;
  gender: string | null;
  type: 'provider' | 'manager';
}

interface CustomersTableProps {
  count?: number;
  page?: number;
  rows?: Customer[];
  rowsPerPage?: number;
  onRowClick?: (id: string) => void;
  onTagUpdated: () => void; // Function to trigger data refetch in the parent

}

export function CustomersTable({
  count = 0,
  rows = [],
  page = 0,
  rowsPerPage = 0,
  // onRowClick,
  onTagUpdated
}: CustomersTableProps): React.JSX.Element {
  const rowIds = React.useMemo(() => {
    return rows.map((customer) => customer.id);
  }, [rows]);

  const { selectAll, deselectAll, selectOne, deselectOne, selected } = useSelection(rowIds);

  const selectedSome = (selected?.size ?? 0) > 0 && (selected?.size ?? 0) < rows.length;
  const selectedAll = rows.length > 0 && selected?.size === rows.length;
  // const router = useRouter();

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
  const [assignModalOpen, setAssignModalOpen] = useState(false);
  const [assignType, setAssignType] = useState<'provider' | 'manager' | null>(null);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error'>('error');
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [assignCategory, setAssignCategory] = useState<string | null>(null);

  const [patientLat, setPatientLat] = useState<string | null>(null);
  const [patientLng, setPatientLng] = useState<string | null>(null);
  const [patientAddress, setPatientAddress] = useState<string | null>(null);
  const [gender, setGender] = useState<string | null>(null);
  const [patientName, setPatientName] = useState<string | null>(null);



  const handleOpenModal = (userId: string) => {
    setSelectedUserId(userId);
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setSelectedUserId(null);
  };

  // Function to open assign modal
  const handleAssign = ({
    userId,
    category,
    patientLat,
    patientLng,
    patientName,
    patientAddress,
    gender,
    type,
  }: AssignParams) => {
    setSelectedUserId(userId);
    setAssignType(type);
    setAssignModalOpen(true);
    setPatientLat(patientLat);
    setPatientLng(patientLng);
    setPatientName(patientName);
    setPatientAddress(patientAddress);
    setGender(gender);
    setAssignCategory(category);
  };
  const onShowBanner = (message: string, severity: 'success' | 'error') => {
    setSnackbarMessage(message);
    setSnackbarSeverity(severity);
    setSnackbarOpen(true);
  };
  const handleLocalTagUpdated = () => {
    // Call the parent's refetch function
    onTagUpdated();
  };

  return (
    <>
      <Card>
        <Box sx={{ overflowX: 'auto' }}>
          <Table sx={{ minWidth: '800px' }}>
            <TableHead>
              <TableRow>
                <TableCell padding="checkbox">
                  <Checkbox
                    checked={selectedAll}
                    indeterminate={selectedSome}
                    onChange={(event) => {
                      if (event.target.checked) {
                        selectAll();
                      } else {
                        deselectAll();
                      }
                    }}
                  />
                </TableCell>
                <TableCell>Company</TableCell>
                <TableCell>Name</TableCell>
                <TableCell>Status</TableCell>
                <TableCell>Address</TableCell>
                <TableCell>Zip Code</TableCell>
                <TableCell>Phone</TableCell>
                <TableCell>DOB</TableCell>
                <TableCell>Visits</TableCell>

                <TableCell>Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {rows.map((row) => {
                const isSelected = selected?.has(row.id);
                return (
                  <TableRow
                    hover
                    key={row.id}
                    selected={isSelected}
                    sx={{ cursor: 'pointer' }}
                    onClick={(event) => event.stopPropagation()}
                  >
                    <TableCell padding="checkbox">
                      <Checkbox
                        checked={isSelected}
                        onChange={(event) => {
                          event.stopPropagation();
                          if (event.target.checked) {
                            selectOne(row.id);
                          } else {
                            deselectOne(row.id);
                          }
                        }}
                      />
                    </TableCell>
                    <TableCell>{row.company_name}</TableCell>


                    <TableCell>
                      <Stack sx={{ alignItems: 'center' }} direction="row" spacing={2}>
                        <Avatar src={row.avatar} />
                        <Typography variant="subtitle2">{row.name}</Typography>
                      </Stack>
                    </TableCell>
                    <TableCell>{row.user_status?row.user_status:'N/A'}</TableCell>
 
                    <TableCell>{`${row.city?row.city:''}, ${row.state?row.state:''}, ${row.address?row.address:''}`}</TableCell>
                    <TableCell>{row.z_code}</TableCell>

                    <TableCell>{row.mobile_number}</TableCell>
                    <TableCell>{row.dob}</TableCell>

                    <TableCell>{row.total_pending_appointments} / {row.total_complete_appointments}</TableCell>
                    <TableCell>
                      <RowActions 
                        rowId={row.id} 
                        category={row.category}
                        onBroadcastClick={handleOpenModal} 
                        onAssignClick={(id, category, type) => 
                          handleAssign({
                            userId: id,
                            category: category ?? null,
                            patientLat: row.lat ?? null,
                            patientLng: row.lng ?? null,
                            patientName: row.name ?? null,
                            patientAddress: row.address ?? null,
                            gender: row.gender ?? null,
                            type,
                          })
                        }
                        onShowBanner={onShowBanner} 
                        onTagUpdated={handleLocalTagUpdated}

                      />
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </Box>
        <Divider />
        <TablePagination
          component="div"
          count={count}
          onPageChange={noop}
          onRowsPerPageChange={noop}
          page={page}
          rowsPerPage={rowsPerPage}
          rowsPerPageOptions={[5, 10, 25]}
        />
      </Card>
      {selectedUserId && (
        <BroadcastModal
          open={isModalOpen}
          onClose={handleCloseModal}
          userId={selectedUserId}
        />
      )}
      {assignType && selectedUserId && (
        <AssignModal
          open={assignModalOpen}
          onClose={() => setAssignModalOpen(false)}
          userId={selectedUserId!}
          type={assignType}
          patientLat={patientLat} // ✅ Add this
          patientLng={patientLng} // ✅ Add this
          patientAddress={patientAddress}
          patientName={patientName}
          gender={gender}

        />
      )}
         <Snackbar
  open={snackbarOpen}
  autoHideDuration={4000}
  onClose={() => setSnackbarOpen(false)}
  anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
>
  <Alert onClose={() => setSnackbarOpen(false)} severity={snackbarSeverity} variant="filled" sx={{ width: '100%' }}>
    {snackbarMessage}
  </Alert>
</Snackbar>
    </>
  );
}
