import DownloadIcon from '@mui/icons-material/Download';
import FilterListIcon from '@mui/icons-material/FilterList';
import {
  Box,
  Button,
  IconButton,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
  TableSortLabel,
  Typography,
  TextField,
} from '@mui/material';
import { DatePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { format } from 'date-fns';
import React, { useEffect, useState } from 'react';

// Sample data - replace with your actual data source
const sampleCalls = [
  {
    id: 1,
    date: '2025-04-20',
    time: '09:30',
    callerNumber: '555-123-4567',
    patientName: 'John Smith',
    callDuration: Math.floor(Math.random() * 60),
  },
  {
    id: 2,
    date: '2025-04-21',
    time: '10:15',
    callerNumber: '555-234-5678',
    patientName: 'Jane Doe',
    callDuration: Math.floor(Math.random() * 60),
  },
  {
    id: 3,
    date: '2025-04-19',
    time: '14:45',
    callerNumber: '555-345-6789',
    patientName: 'Robert Johnson',
    callDuration: Math.floor(Math.random() * 60),
  },
  {
    id: 4,
    date: '2025-04-22',
    time: '11:00',
    callerNumber: '555-456-7890',
    patientName: 'Emily Davis',
    callDuration: Math.floor(Math.random() * 60),
  },
  {
    id: 5,
    date: '2025-04-20',
    time: '16:30',
    callerNumber: '555-567-8901',
    patientName: 'Michael Brown',
    callDuration: Math.floor(Math.random() * 60),
  },
  {
    id: 6,
    date: '2025-04-19',
    time: '14:45',
    callerNumber: '555-345-6789',
    patientName: 'Robert Johnson',
    callDuration: Math.floor(Math.random() * 60),
  },
  {
    id: 7,
    date: '2025-04-22',
    time: '11:00',
    callerNumber: '555-456-7890',
    patientName: 'Emily Davis',
    callDuration: Math.floor(Math.random() * 60),
  },
  {
    id: 8,
    date: '2025-04-20',
    time: '16:30',
    callerNumber: '555-567-8901',
    patientName: 'Michael Brown',
    callDuration: Math.floor(Math.random() * 60),
  },
  {
    id: 9,
    date: '2025-04-19',
    time: '14:45',
    callerNumber: '555-345-6789',
    patientName: 'Robert Johnson',
    callDuration: Math.floor(Math.random() * 60),
  },
  {
    id: 10,
    date: '2025-04-22',
    time: '11:00',
    callerNumber: '555-456-7890',
    patientName: 'Emily Davis',
    callDuration: Math.floor(Math.random() * 60),
  },
  {
    id: 11,
    date: '2025-04-20',
    time: '16:30',
    callerNumber: '555-567-8901',
    patientName: 'Michael Brown',
    callDuration: Math.floor(Math.random() * 60),
  },
];

const CallListTable = () => {
  const [calls, setCalls] = useState([]);
  const [orderBy, setOrderBy] = useState('date');
  const [order, setOrder] = useState('desc');
  const [showFilters, setShowFilters] = useState(false);
  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);

  // Pagination state
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(5);

  // Initialize with sample data
  useEffect(() => {
    setCalls(sampleCalls);
  }, []);

  // Handle sort request
  const handleRequestSort = (property) => {
    const isAsc = orderBy === property && order === 'asc';
    setOrder(isAsc ? 'desc' : 'asc');
    setOrderBy(property);
  };

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    const day = date.getDate().toString().padStart(2, '0');
    const month = date.toLocaleString('en-US', { month: 'short' });
    const year = date.getFullYear();
    return `${day}-${month}-${year}`;
  };

  // Handle download transcript
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleDownloadTranscript = (id) => {
    // TODO: Implement actual download functionality here
  };

  // Apply filters
  const applyFilters = () => {
    let filteredCalls = [...sampleCalls];

    if (startDate) {
      const startDateStr = format(startDate, 'yyyy-MM-dd');
      filteredCalls = filteredCalls.filter((call) => call.date >= startDateStr);
    }

    if (endDate) {
      const endDateStr = format(endDate, 'yyyy-MM-dd');
      filteredCalls = filteredCalls.filter((call) => call.date <= endDateStr);
    }

    setCalls(filteredCalls);
    setPage(0); // Reset to first page after filtering
  };

  // Reset filters
  const resetFilters = () => {
    setStartDate(null);
    setEndDate(null);
    setCalls(sampleCalls);
    setPage(0); // Reset to first page after clearing filters
  };

  // Handle page change
  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  // Handle rows per page change
  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  // Sort function
  const sortedCalls = calls.sort((a, b) => {
    if (orderBy === 'date') {
      const dateComparison = a.date.localeCompare(b.date);
      if (dateComparison !== 0)
        return order === 'asc' ? dateComparison : -dateComparison;

      // If dates are equal, sort by time
      return order === 'asc'
        ? a.time.localeCompare(b.time)
        : b.time.localeCompare(a.time);
    }

    if (orderBy === 'time') {
      return order === 'asc'
        ? a.time.localeCompare(b.time)
        : b.time.localeCompare(a.time);
    }

    return 0;
  });

  // Get current page data
  const currentPageCalls = sortedCalls.slice(
    page * rowsPerPage,
    page * rowsPerPage + rowsPerPage
  );

  // Custom render function for DatePicker to avoid renderInput prop issues
  const CustomDateField = ({ value, onChange, label }) => (
    <TextField
      label={label}
      value={value ? format(value, 'yyyy-MM-dd') : ''}
      onChange={(e) => {
        try {
          const dateStr = e.target.value;
          const date = new Date(dateStr);
          if (!isNaN(date.getTime())) {
            onChange(date);
          }
        } catch (error) {
          // Invalid date
        }
      }}
      placeholder="YYYY-MM-DD"
      size="small"
      sx={{ minWidth: 200 }}
    />
  );

  return (
    <Box sx={{ width: '100%' }}>
      <Paper sx={{ width: '100%', mb: 2 }}>
        <Box
          sx={{
            p: 2,
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <Typography variant="h6" component="div">
            Call Transcripts
          </Typography>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <Button
              variant="contained"
              color="primary"
              startIcon={<DownloadIcon />}
              onClick={() => {
                /* TODO: Implement bulk download */
              }}
              sx={{ bgcolor: '#f5365c', '&:hover': { bgcolor: '#d40639' } }}
            >
              Bulk Download
            </Button>
            <Button
              startIcon={<FilterListIcon />}
              onClick={() => setShowFilters(!showFilters)}
              color={showFilters ? 'secondary' : 'primary'}
              sx={{ color: showFilters ? '#f5365c' : undefined }}
            >
              {showFilters ? 'Hide Filters' : 'Show Filters'}
            </Button>
          </Box>
        </Box>

        {showFilters && (
          <Box
            sx={{
              p: 2,
              display: 'flex',
              gap: 2,
              flexWrap: 'wrap',
              alignItems: 'center',
            }}
          >
            <LocalizationProvider dateAdapter={AdapterDateFns}>
              <Box>
                <CustomDateField
                  label="Start Date (YYYY-MM-DD)"
                  value={startDate}
                  onChange={setStartDate}
                />
              </Box>

              <Box>
                <CustomDateField
                  label="End Date (YYYY-MM-DD)"
                  value={endDate}
                  onChange={setEndDate}
                />
              </Box>
            </LocalizationProvider>

            <Button
              variant="contained"
              onClick={applyFilters}
              sx={{ bgcolor: '#f5365c', '&:hover': { bgcolor: '#d40639' } }}
            >
              Apply Filters
            </Button>
            <Button
              variant="outlined"
              onClick={resetFilters}
              sx={{
                color: '#f5365c',
                borderColor: '#f5365c',
                '&:hover': { borderColor: '#d40639' },
              }}
            >
              Reset
            </Button>
          </Box>
        )}

        <TableContainer>
          <Table sx={{ minWidth: 750 }} aria-labelledby="callListTable">
            <TableHead>
              <TableRow>
                <TableCell>
                  <TableSortLabel
                    active={orderBy === 'date'}
                    direction={orderBy === 'date' ? order : 'asc'}
                    onClick={() => handleRequestSort('date')}
                  >
                    Date
                  </TableSortLabel>
                </TableCell>
                <TableCell>
                  <TableSortLabel
                    active={orderBy === 'time'}
                    direction={orderBy === 'time' ? order : 'asc'}
                    onClick={() => handleRequestSort('time')}
                  >
                    Received Time
                  </TableSortLabel>
                </TableCell>
                <TableCell>Call Duration</TableCell>
                <TableCell>Caller Number</TableCell>
                <TableCell>Patient Name</TableCell>
                <TableCell align="center">Action</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {currentPageCalls.map((call) => (
                <TableRow key={call.id}>
                  <TableCell component="th" scope="row">
                    {formatDate(call.date)}
                  </TableCell>
                  <TableCell>{call.time}</TableCell>
                  <TableCell>{call.callDuration} Sec</TableCell>
                  <TableCell>{call.callerNumber}</TableCell>
                  <TableCell>{call.patientName}</TableCell>
                  <TableCell align="center">
                    <IconButton
                      color="primary"
                      onClick={() => handleDownloadTranscript(call.id)}
                      aria-label="download transcript"
                      sx={{ color: '#f5365c' }}
                    >
                      <DownloadIcon />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {currentPageCalls.length === 0 && (
                <TableRow>
                  <TableCell colSpan={5} align="center">
                    No calls found
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>

        <TablePagination
          rowsPerPageOptions={[5, 10, 25]}
          component="div"
          count={sortedCalls.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        />
      </Paper>
    </Box>
  );
};

export default CallListTable;
