import React, { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  TextField,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  IconButton,
  Tooltip,
  Chip,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Publish as PublishIcon,
  Search as SearchIcon,
  FilterList as FilterIcon,
} from '@mui/icons-material';
import { usePackages, useDeletePackage } from '../../hooks/usePackages';
import { useProjects } from '../../hooks/useProjects';
import { Package, PackageStatus, PackageFilter } from '../../types';
import { StatusChip } from '../common/StatusChip';
import { LoadingSpinner } from '../common/LoadingSpinner';
import { ErrorDisplay } from '../common/ErrorDisplay';
import { format } from 'date-fns';

interface PackageListProps {
  onCreatePackage: () => void;
  onEditPackage: (packageItem: Package) => void;
  onPublishPackage: (packageItem: Package) => void;
}

export const PackageList: React.FC<PackageListProps> = ({
  onCreatePackage,
  onEditPackage,
  onPublishPackage,
}) => {
  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [filter, setFilter] = useState<PackageFilter>({});
  const [showFilters, setShowFilters] = useState(false);

  const { data: packagesData, isLoading, error, refetch } = usePackages(
    page + 1,
    pageSize,
    filter
  );
  const { data: projectsData } = useProjects();
  const deletePackageMutation = useDeletePackage();

  const handleFilterChange = (field: keyof PackageFilter, value: any) => {
    setFilter(prev => ({ ...prev, [field]: value }));
    setPage(0);
  };

  const handleDelete = async (id: number) => {
    if (window.confirm('Are you sure you want to delete this package?')) {
      await deletePackageMutation.mutateAsync(id);
    }
  };

  const canPublish = (pkg: Package): boolean => {
    return pkg.status === PackageStatus.Ready || pkg.status === PackageStatus.Failed;
  };

  const canEdit = (pkg: Package): boolean => {
    return pkg.status !== PackageStatus.Publishing;
  };

  if (isLoading) return <LoadingSpinner message="Loading packages..." />;
  if (error) return <ErrorDisplay message="Failed to load packages" onRetry={refetch} />;

  const packages = packagesData?.data || [];
  const totalCount = packagesData?.totalCount || 0;

  return (
    <Box>
      {/* Header */}
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Typography variant="h4" component="h1">
          Packages
        </Typography>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={onCreatePackage}
        >
          Create Package
        </Button>
      </Box>

      {/* Filters */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Box display="flex" alignItems="center" gap={2} mb={showFilters ? 2 : 0}>
            <TextField
              placeholder="Search packages..."
              variant="outlined"
              size="small"
              value={filter.searchTerm || ''}
              onChange={(e) => handleFilterChange('searchTerm', e.target.value)}
              InputProps={{
                startAdornment: <SearchIcon sx={{ mr: 1, color: 'text.secondary' }} />,
              }}
            />
            <Button
              variant="outlined"
              startIcon={<FilterIcon />}
              onClick={() => setShowFilters(!showFilters)}
            >
              {showFilters ? 'Hide Filters' : 'Show Filters'}
            </Button>
          </Box>

          {showFilters && (
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6} md={3}>
                <FormControl fullWidth size="small">
                  <InputLabel>Project</InputLabel>
                  <Select
                    value={filter.projectId || ''}
                    onChange={(e) => handleFilterChange('projectId', e.target.value || undefined)}
                    label="Project"
                  >
                    <MenuItem value="">All Projects</MenuItem>
                    {projectsData?.data?.map((project) => (
                      <MenuItem key={project.id} value={project.id}>
                        {project.name}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>
              <Grid item xs={12} sm={6} md={3}>
                <FormControl fullWidth size="small">
                  <InputLabel>Status</InputLabel>
                  <Select
                    value={filter.status || ''}
                    onChange={(e) => handleFilterChange('status', e.target.value || undefined)}
                    label="Status"
                  >
                    <MenuItem value="">All Statuses</MenuItem>
                    {Object.values(PackageStatus).map((status) => (
                      <MenuItem key={status} value={status}>
                        {status}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>
            </Grid>
          )}
        </CardContent>
      </Card>

      {/* Packages Table */}
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Title</TableCell>
              <TableCell>Version</TableCell>
              <TableCell>Project</TableCell>
              <TableCell>Status</TableCell>
              <TableCell>Published Date</TableCell>
              <TableCell>Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {packages.map((pkg) => (
              <TableRow key={pkg.id} hover>
                <TableCell>
                  <Box>
                    <Typography variant="subtitle2">{pkg.title}</Typography>
                    <Typography variant="body2" color="text.secondary">
                      {pkg.description}
                    </Typography>
                  </Box>
                </TableCell>
                <TableCell>
                  <Chip label={pkg.version} variant="outlined" size="small" />
                </TableCell>
                <TableCell>{pkg.project?.name || 'Unknown'}</TableCell>
                <TableCell>
                  <StatusChip status={pkg.status} />
                </TableCell>
                <TableCell>
                  {pkg.publishDate ? format(new Date(pkg.publishDate), 'MMM dd, yyyy HH:mm') : '-'}
                </TableCell>
                <TableCell>
                  <Box display="flex" gap={1}>
                    {canEdit(pkg) && (
                      <Tooltip title="Edit Package">
                        <IconButton
                          size="small"
                          onClick={() => onEditPackage(pkg)}
                        >
                          <EditIcon />
                        </IconButton>
                      </Tooltip>
                    )}
                    {canPublish(pkg) && (
                      <Tooltip title="Publish Package">
                        <IconButton
                          size="small"
                          color="primary"
                          onClick={() => onPublishPackage(pkg)}
                        >
                          <PublishIcon />
                        </IconButton>
                      </Tooltip>
                    )}
                    {canEdit(pkg) && (
                      <Tooltip title="Delete Package">
                        <IconButton
                          size="small"
                          color="error"
                          onClick={() => handleDelete(pkg.id)}
                          disabled={deletePackageMutation.isPending}
                        >
                          <DeleteIcon />
                        </IconButton>
                      </Tooltip>
                    )}
                  </Box>
                </TableCell>
              </TableRow>
            ))}
            {packages.length === 0 && (
              <TableRow>
                <TableCell colSpan={6} align="center" sx={{ py: 4 }}>
                  <Typography variant="body2" color="text.secondary">
                    No packages found. Create your first package to get started.
                  </Typography>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
        <TablePagination
          component="div"
          count={totalCount}
          page={page}
          onPageChange={(_, newPage) => setPage(newPage)}
          rowsPerPage={pageSize}
          onRowsPerPageChange={(e) => {
            setPageSize(parseInt(e.target.value, 10));
            setPage(0);
          }}
          rowsPerPageOptions={[5, 10, 25, 50]}
        />
      </TableContainer>
    </Box>
  );
};