'use client';

import React from 'react';
import {
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  TableSortLabel,
  Chip,
  Avatar,
  Typography,
  IconButton,
  Tooltip,
  Paper,
  useTheme,
} from '@mui/material';
import { AppLoader } from '@/components/core/app-loader';
import {
  Email as EmailIcon,
  Phone as PhoneIcon,
  LocationOn as LocationIcon,
  CalendarToday as CalendarIcon,
  Person as PersonIcon,
} from '@mui/icons-material';
import {
  NewsletterSubscriber,
  NewsletterPagination,
} from '@/services/newsletter.service';

interface NewsletterTableProps {
  subscribers: NewsletterSubscriber[];
  pagination?: NewsletterPagination;
  loading?: boolean;
  onPageChange: (page: number) => void;
  onRowsPerPageChange: (rowsPerPage: number) => void;
  onSort: (field: string, direction: 'asc' | 'desc') => void;
  currentSort: {
    sortBy: string;
    sortOrder: 'asc' | 'desc';
  };
}

interface Column {
  id: keyof NewsletterSubscriber | 'subscriptionStatus';
  label: string;
  minWidth?: number;
  sortable?: boolean;
  align?: 'left' | 'center' | 'right';
}

const columns: Column[] = [
  { id: 'fullName', label: 'Subscriber', minWidth: 200, sortable: true },
  { id: 'emailAddress', label: 'Email', minWidth: 200, sortable: true },
  { id: 'phoneNumber', label: 'Phone', minWidth: 150, sortable: false },
  { id: 'address', label: 'Address', minWidth: 150, sortable: false },
  { id: 'subscriptionStatus', label: 'Subscription', minWidth: 150, sortable: false },
  { id: 'status', label: 'Status', minWidth: 100, sortable: true },
  { id: 'userAccountType', label: 'Type', minWidth: 100, sortable: true },
  { id: 'subscriptionDate', label: 'Subscribed', minWidth: 120, sortable: true },
  { id: 'lastUpdated', label: 'Last Updated', minWidth: 120, sortable: true },
];

function getInitials(name: string): string {
  return name
    .split(' ')
    .map(word => word.charAt(0))
    .join('')
    .toUpperCase()
    .slice(0, 2);
}

function formatDate(dateString: string): string {
  try {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  } catch (error) {
    return 'Invalid Date';
  }
}

function SubscriptionStatusChips({ subscriber }: { subscriber: NewsletterSubscriber }) {
  return (
    <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
      {subscriber.isEmailSubscribed && (
        <Chip
          icon={<EmailIcon />}
          label="Email"
          size="small"
          color="primary"
          variant="outlined"
        />
      )}
      {subscriber.isPhoneSubscribed && (
        <Chip
          icon={<PhoneIcon />}
          label="Phone"
          size="small"
          color="secondary"
          variant="outlined"
        />
      )}
      {!subscriber.isEmailSubscribed && !subscriber.isPhoneSubscribed && (
        <Chip
          label="None"
          size="small"
          color="default"
          variant="outlined"
        />
      )}
    </Box>
  );
}

function AddressDisplay({ subscriber }: { subscriber: NewsletterSubscriber }) {
  if (!subscriber.address) {
    return <Typography variant="body2" color="text.secondary">N/A</Typography>;
  }

  return (
    <Box sx={{ display: 'flex', alignItems: 'center' }}>
      <LocationIcon sx={{ fontSize: 16, mr: 0.5, color: 'text.secondary' }} />
      <Typography variant="body2" noWrap>
        {subscriber.address}
      </Typography>
    </Box>
  );
}

function StatusChip({ status }: { status: string }) {
  const getStatusColor = (status: string): 'success' | 'error' | 'default' => {
    switch (status.toLowerCase()) {
      case 'accepted':
        return 'success';
      case 'deleted':
        return 'error';
      default:
        return 'default';
    }
  };

  return (
    <Chip
      label={status.charAt(0).toUpperCase() + status.slice(1)}
      size="small"
      color={getStatusColor(status)}
      variant="outlined"
    />
  );
}

function SubscriberNameCell({ subscriber }: { subscriber: NewsletterSubscriber }) {
  const theme = useTheme();
  
  return (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
      <Avatar
        sx={{
          width: 40,
          height: 40,
          bgcolor: theme.palette.primary.main,
          fontSize: '0.875rem',
          fontWeight: 600,
        }}
      >
        {getInitials(subscriber.fullName || 'Unknown')}
      </Avatar>
      <Box>
        <Typography variant="subtitle2" fontWeight={600}>
          {subscriber.fullName || 'Unknown User'}
        </Typography>
      </Box>
    </Box>
  );
}

export function NewsletterTable({
  subscribers,
  pagination,
  loading = false,
  onPageChange,
  onRowsPerPageChange,
  onSort,
  currentSort,
}: NewsletterTableProps) {
  const theme = useTheme();

  const handleSort = (columnId: string) => {
    if (columnId === currentSort.sortBy) {
      onSort(columnId, currentSort.sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      onSort(columnId, 'desc');
    }
  };

  const handleChangePage = (event: unknown, newPage: number) => {
    onPageChange(newPage + 1); // Convert to 1-based indexing
  };

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    onRowsPerPageChange(parseInt(event.target.value, 10));
  };

  if (loading && subscribers.length === 0) {
    return (
      <Paper sx={{ position: 'relative', width: '100%', minHeight: 400, overflow: 'hidden' }}>
        <AppLoader fill size="lg" />
      </Paper>
    );
  }

  return (
    <Paper sx={{ width: '100%', overflow: 'hidden' }}>
      <TableContainer sx={{ maxHeight: 600 }}>
        <Table stickyHeader>
          <TableHead>
            <TableRow>
              {columns.map((column) => (
                <TableCell
                  key={column.id}
                  align={column.align}
                  style={{ minWidth: column.minWidth }}
                  sx={{
                    backgroundColor: theme.palette.grey[50],
                    fontWeight: 600,
                  }}
                >
                  {column.sortable ? (
                    <TableSortLabel
                      active={currentSort.sortBy === column.id}
                      direction={
                        currentSort.sortBy === column.id
                          ? currentSort.sortOrder
                          : 'desc'
                      }
                      onClick={() => handleSort(column.id as string)}
                    >
                      {column.label}
                    </TableSortLabel>
                  ) : (
                    column.label
                  )}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {subscribers.length === 0 && !loading ? (
              <TableRow>
                <TableCell colSpan={columns.length} align="center" sx={{ py: 6 }}>
                  <Typography variant="body1" color="text.secondary">
                    No newsletter subscribers found
                  </Typography>
                </TableCell>
              </TableRow>
            ) : (
              subscribers.map((subscriber) => (
                <TableRow hover key={subscriber._id}>
                  <TableCell>
                    <SubscriberNameCell subscriber={subscriber} />
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                      <EmailIcon sx={{ fontSize: 16, mr: 1, color: 'text.secondary' }} />
                      <Typography variant="body2" noWrap>
                        {subscriber.emailAddress}
                      </Typography>
                    </Box>
                  </TableCell>
                  <TableCell>
                    {subscriber.phoneNumber ? (
                      <Box sx={{ display: 'flex', alignItems: 'center' }}>
                        <PhoneIcon sx={{ fontSize: 16, mr: 1, color: 'text.secondary' }} />
                        <Typography variant="body2">
                          {subscriber.phoneNumber}
                        </Typography>
                      </Box>
                    ) : (
                      <Typography variant="body2" color="text.secondary">
                        N/A
                      </Typography>
                    )}
                  </TableCell>
                  <TableCell>
                    <AddressDisplay subscriber={subscriber} />
                  </TableCell>
                  <TableCell>
                    <SubscriptionStatusChips subscriber={subscriber} />
                  </TableCell>
                  <TableCell>
                    <StatusChip status={subscriber.status} />
                  </TableCell>
                  <TableCell>
                    <Chip
                      label={subscriber.userAccountType}
                      size="small"
                      variant="outlined"
                      color={subscriber.userAccountType === 'Admin' ? 'error' : 'default'}
                    />
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                      <CalendarIcon sx={{ fontSize: 16, mr: 1, color: 'text.secondary' }} />
                      <Typography variant="body2">
                        {formatDate(subscriber.subscriptionDate)}
                      </Typography>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2" color="text.secondary">
                      {formatDate(subscriber.lastUpdated)}
                    </Typography>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>

      {pagination && (
        <TablePagination
          rowsPerPageOptions={[5, 10, 25, 50, 100]}
          component="div"
          count={pagination.totalCount}
          rowsPerPage={pagination.limit}
          page={(pagination.currentPage || 1) - 1} // Convert to 0-based indexing
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
          labelRowsPerPage="Rows per page:"
          labelDisplayedRows={({ from, to, count }) =>
            `${from}-${to} of ${count !== -1 ? count : `more than ${to}`}`
          }
          sx={{
            borderTop: `1px solid ${theme.palette.divider}`,
            '& .MuiTablePagination-toolbar': {
              px: 2,
            },
          }}
        />
      )}
    </Paper>
  );
}
