/**
 * Court Filing Component
 * UI for court filing management
 */

import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  Box,
  Button,
  Card,
  CardContent,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Alert,
} from '@mui/material';
import { Add as AddIcon, CalendarToday as CalendarIcon } from '@mui/icons-material';

interface Filing {
  id: string;
  document_id: string;
  matter_id: string;
  court_name: string;
  case_number?: string;
  filing_type: string;
  status: string;
  filing_deadline?: string;
}

export function CourtFiling({ matterId }: { matterId: string }) {
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const queryClient = useQueryClient();

  const { data: filings } = useQuery<Filing[]>({
    queryKey: ['filings', matterId],
    queryFn: async () => {
      const response = await fetch(`/api/filings?matter_id=${matterId}`);
      const data = await response.json();
      return data.filings || [];
    },
  });

  const { data: deadlines } = useQuery<Filing[]>({
    queryKey: ['filing-deadlines', matterId],
    queryFn: async () => {
      const response = await fetch(`/api/matters/${matterId}/filing-deadlines`);
      const data = await response.json();
      return data.deadlines || [];
    },
  });

  const createFiling = useMutation({
    mutationFn: async (filing: Partial<Filing>) => {
      const response = await fetch('/api/filings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(filing),
      });
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['filings', matterId] });
      setCreateDialogOpen(false);
    },
  });

  const handleCreateFiling = (formData: FormData) => {
    createFiling.mutate({
      matter_id: matterId,
      document_id: formData.get('document_id') as string,
      court_name: formData.get('court_name') as string,
      case_number: formData.get('case_number') as string,
      filing_type: formData.get('filing_type') as string,
      filing_deadline: formData.get('filing_deadline') as string,
    });
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'filed':
        return 'success';
      case 'accepted':
        return 'success';
      case 'rejected':
        return 'error';
      case 'submitted':
        return 'info';
      default:
        return 'default';
    }
  };

  return (
    <Box>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Typography variant="h5">Court Filings</Typography>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={() => setCreateDialogOpen(true)}
        >
          New Filing
        </Button>
      </Box>

      {deadlines && deadlines.length > 0 && (
        <Alert severity="warning" sx={{ mb: 3 }}>
          <Typography variant="subtitle2">Upcoming Deadlines</Typography>
          {deadlines.map((deadline) => (
            <Typography key={deadline.id} variant="body2">
              {deadline.court_name}: {new Date(deadline.filing_deadline!).toLocaleDateString()}
            </Typography>
          ))}
        </Alert>
      )}

      <Card>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Court</TableCell>
              <TableCell>Case Number</TableCell>
              <TableCell>Type</TableCell>
              <TableCell>Status</TableCell>
              <TableCell>Deadline</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {filings?.map((filing) => (
              <TableRow key={filing.id}>
                <TableCell>{filing.court_name}</TableCell>
                <TableCell>{filing.case_number || 'N/A'}</TableCell>
                <TableCell>{filing.filing_type}</TableCell>
                <TableCell>
                  <Chip label={filing.status} size="small" color={getStatusColor(filing.status)} />
                </TableCell>
                <TableCell>
                  {filing.filing_deadline ? (
                    <Box display="flex" alignItems="center">
                      <CalendarIcon sx={{ mr: 1, fontSize: 16 }} />
                      {new Date(filing.filing_deadline).toLocaleDateString()}
                    </Box>
                  ) : (
                    'N/A'
                  )}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Card>

      <Dialog open={createDialogOpen} onClose={() => setCreateDialogOpen(false)} maxWidth="sm" fullWidth>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            handleCreateFiling(new FormData(e.currentTarget));
          }}
        >
          <DialogTitle>Create Court Filing</DialogTitle>
          <DialogContent>
            <TextField
              autoFocus
              margin="dense"
              name="document_id"
              label="Document ID"
              fullWidth
              required
              sx={{ mb: 2 }}
            />
            <TextField
              margin="dense"
              name="court_name"
              label="Court Name"
              fullWidth
              required
              sx={{ mb: 2 }}
            />
            <TextField
              margin="dense"
              name="case_number"
              label="Case Number"
              fullWidth
              sx={{ mb: 2 }}
            />
            <FormControl fullWidth margin="dense" sx={{ mb: 2 }}>
              <InputLabel>Filing Type</InputLabel>
              <Select name="filing_type" label="Filing Type" required>
                <MenuItem value="pleading">Pleading</MenuItem>
                <MenuItem value="motion">Motion</MenuItem>
                <MenuItem value="brief">Brief</MenuItem>
                <MenuItem value="exhibit">Exhibit</MenuItem>
                <MenuItem value="affidavit">Affidavit</MenuItem>
              </Select>
            </FormControl>
            <TextField
              margin="dense"
              name="filing_deadline"
              label="Filing Deadline"
              type="date"
              fullWidth
              InputLabelProps={{ shrink: true }}
            />
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setCreateDialogOpen(false)}>Cancel</Button>
            <Button type="submit" variant="contained">
              Create Filing
            </Button>
          </DialogActions>
        </form>
      </Dialog>
    </Box>
  );
}

