/**
 * Matter Management Component
 * UI for legal matter management
 */

import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  IconButton,
  Tabs,
  Tab,
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Folder as FolderIcon,
  People as PeopleIcon,
  Description as DescriptionIcon,
} from '@mui/icons-material';
import { DocumentManagement } from './DocumentManagement';

interface Matter {
  id: string;
  matter_number: string;
  title: string;
  status: string;
  matter_type?: string;
  client_id?: string;
  created_at: string;
}

export function MatterManagement() {
  const [selectedMatter, setSelectedMatter] = useState<Matter | null>(null);
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [tabValue, setTabValue] = useState(0);
  const queryClient = useQueryClient();

  const { data: matters, isLoading } = useQuery<Matter[]>({
    queryKey: ['matters'],
    queryFn: async () => {
      const response = await fetch('/api/matters');
      if (!response.ok) throw new Error('Failed to fetch matters');
      const data = await response.json();
      return data.matters || [];
    },
  });

  const createMatter = useMutation({
    mutationFn: async (matter: Partial<Matter>) => {
      const response = await fetch('/api/matters', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(matter),
      });
      if (!response.ok) throw new Error('Failed to create matter');
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['matters'] });
      setCreateDialogOpen(false);
    },
  });

  const handleCreateMatter = (formData: FormData) => {
    createMatter.mutate({
      matter_number: formData.get('matter_number') as string,
      title: formData.get('title') as string,
      description: formData.get('description') as string,
      matter_type: formData.get('matter_type') as string,
      status: 'open',
    });
  };

  return (
    <Box>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Typography variant="h4">Legal Matters</Typography>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={() => setCreateDialogOpen(true)}
        >
          New Matter
        </Button>
      </Box>

      {selectedMatter ? (
        <Box>
          <Box display="flex" alignItems="center" mb={2}>
            <IconButton onClick={() => setSelectedMatter(null)}>←</IconButton>
            <Typography variant="h5">{selectedMatter.title}</Typography>
            <Chip label={selectedMatter.status} sx={{ ml: 2 }} />
          </Box>

          <Tabs value={tabValue} onChange={(_, v) => setTabValue(v)}>
            <Tab icon={<DescriptionIcon />} label="Documents" />
            <Tab icon={<PeopleIcon />} label="Participants" />
            <Tab icon={<FolderIcon />} label="Details" />
          </Tabs>

          <Box mt={3}>
            {tabValue === 0 && <DocumentManagement matterId={selectedMatter.id} />}
            {tabValue === 1 && <Typography>Participants coming soon</Typography>}
            {tabValue === 2 && (
              <Card>
                <CardContent>
                  <Typography variant="h6">Matter Details</Typography>
                  <Typography>Number: {selectedMatter.matter_number}</Typography>
                  <Typography>Type: {selectedMatter.matter_type || 'N/A'}</Typography>
                  <Typography>Status: {selectedMatter.status}</Typography>
                </CardContent>
              </Card>
            )}
          </Box>
        </Box>
      ) : (
        <>
          {isLoading ? (
            <Typography>Loading...</Typography>
          ) : (
            <Card>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>Matter Number</TableCell>
                    <TableCell>Title</TableCell>
                    <TableCell>Type</TableCell>
                    <TableCell>Status</TableCell>
                    <TableCell>Actions</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {matters?.map((matter) => (
                    <TableRow
                      key={matter.id}
                      onClick={() => setSelectedMatter(matter)}
                      sx={{ cursor: 'pointer' }}
                    >
                      <TableCell>{matter.matter_number}</TableCell>
                      <TableCell>{matter.title}</TableCell>
                      <TableCell>{matter.matter_type || 'N/A'}</TableCell>
                      <TableCell>
                        <Chip label={matter.status} size="small" />
                      </TableCell>
                      <TableCell>
                        <IconButton size="small">
                          <EditIcon />
                        </IconButton>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </Card>
          )}
        </>
      )}

      <Dialog open={createDialogOpen} onClose={() => setCreateDialogOpen(false)} maxWidth="sm" fullWidth>
        <form
          onSubmit={(e) => {
            e.preventDefault();
            handleCreateMatter(new FormData(e.currentTarget));
          }}
        >
          <DialogTitle>Create New Matter</DialogTitle>
          <DialogContent>
            <TextField
              autoFocus
              margin="dense"
              name="matter_number"
              label="Matter Number"
              fullWidth
              required
              sx={{ mb: 2 }}
            />
            <TextField
              margin="dense"
              name="title"
              label="Title"
              fullWidth
              required
              sx={{ mb: 2 }}
            />
            <TextField
              margin="dense"
              name="description"
              label="Description"
              fullWidth
              multiline
              rows={4}
              sx={{ mb: 2 }}
            />
            <TextField
              margin="dense"
              name="matter_type"
              label="Matter Type"
              fullWidth
            />
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setCreateDialogOpen(false)}>Cancel</Button>
            <Button type="submit" variant="contained">
              Create
            </Button>
          </DialogActions>
        </form>
      </Dialog>
    </Box>
  );
}

