/**
 * Document Workflow Component
 * UI for workflow management and approval
 */

import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  Box,
  Button,
  Card,
  CardContent,
  LinearProgress,
  Typography,
  Chip,
  List,
  ListItem,
  ListItemText,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
} from '@mui/material';
import {
  CheckCircle as ApproveIcon,
  Cancel as RejectIcon,
  Assignment as AssignmentIcon,
} from '@mui/icons-material';

interface Workflow {
  id: string;
  document_id: string;
  workflow_type: string;
  status: string;
  steps: WorkflowStep[];
}

interface WorkflowStep {
  id: string;
  step_number: number;
  step_type: string;
  status: string;
  assigned_to?: string;
  due_date?: string;
}

export function DocumentWorkflow({ documentId }: { documentId: string }) {
  const [approvalDialogOpen, setApprovalDialogOpen] = useState(false);
  const [selectedStep, setSelectedStep] = useState<WorkflowStep | null>(null);
  const [comments, setComments] = useState('');
  const queryClient = useQueryClient();

  const { data: workflow } = useQuery<Workflow>({
    queryKey: ['workflow', documentId],
    queryFn: async () => {
      const response = await fetch(`/api/documents/${documentId}/workflows`);
      const data = await response.json();
      return data.workflows?.[0] || null;
    },
  });

  const approveStep = useMutation({
    mutationFn: async ({ stepId, comments: cmts }: { stepId: string; comments?: string }) => {
      const response = await fetch(`/api/workflows/steps/${stepId}/complete`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: 'approved', comments: cmts }),
      });
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['workflow', documentId] });
      setApprovalDialogOpen(false);
    },
  });

  const rejectStep = useMutation({
    mutationFn: async ({ stepId, comments: cmts }: { stepId: string; comments?: string }) => {
      const response = await fetch(`/api/workflows/steps/${stepId}/complete`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: 'rejected', comments: cmts }),
      });
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['workflow', documentId] });
      setApprovalDialogOpen(false);
    },
  });

  if (!workflow) {
    return <Typography>No workflow found for this document</Typography>;
  }

  const completedSteps = workflow.steps?.filter((s) => s.status === 'approved' || s.status === 'rejected').length || 0;
  const totalSteps = workflow.steps?.length || 1;
  const progress = (completedSteps / totalSteps) * 100;

  return (
    <Box>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
        <Typography variant="h6">Workflow: {workflow.workflow_type}</Typography>
        <Chip label={workflow.status} color={workflow.status === 'completed' ? 'success' : 'default'} />
      </Box>

      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="subtitle2" gutterBottom>
            Progress
          </Typography>
          <LinearProgress variant="determinate" value={progress} sx={{ mb: 1 }} />
          <Typography variant="body2" color="text.secondary">
            {completedSteps} of {totalSteps} steps completed
          </Typography>
        </CardContent>
      </Card>

      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            Workflow Steps
          </Typography>
          <List>
            {workflow.steps?.map((step) => (
              <ListItem
                key={step.id}
                secondaryAction={
                  step.status === 'pending' || step.status === 'in_progress' ? (
                    <Box>
                      <Button
                        size="small"
                        startIcon={<ApproveIcon />}
                        color="success"
                        onClick={() => {
                          setSelectedStep(step);
                          setApprovalDialogOpen(true);
                        }}
                      >
                        Approve
                      </Button>
                      <Button
                        size="small"
                        startIcon={<RejectIcon />}
                        color="error"
                        onClick={() => {
                          setSelectedStep(step);
                          setApprovalDialogOpen(true);
                        }}
                      >
                        Reject
                      </Button>
                    </Box>
                  ) : (
                    <Chip
                      label={step.status}
                      size="small"
                      color={step.status === 'approved' ? 'success' : 'error'}
                    />
                  )
                }
              >
                <AssignmentIcon sx={{ mr: 2 }} />
                <ListItemText
                  primary={`Step ${step.step_number}: ${step.step_type}`}
                  secondary={step.due_date ? `Due: ${new Date(step.due_date).toLocaleDateString()}` : ''}
                />
              </ListItem>
            ))}
          </List>
        </CardContent>
      </Card>

      <Dialog open={approvalDialogOpen} onClose={() => setApprovalDialogOpen(false)}>
        <DialogTitle>
          {selectedStep?.status === 'pending' ? 'Approve or Reject Step' : 'Add Comments'}
        </DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            multiline
            rows={4}
            label="Comments"
            value={comments}
            onChange={(e) => setComments(e.target.value)}
            sx={{ mt: 2 }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setApprovalDialogOpen(false)}>Cancel</Button>
          <Button
            color="error"
            onClick={() => {
              if (selectedStep) {
                rejectStep.mutate({ stepId: selectedStep.id, comments });
              }
            }}
          >
            Reject
          </Button>
          <Button
            color="success"
            variant="contained"
            onClick={() => {
              if (selectedStep) {
                approveStep.mutate({ stepId: selectedStep.id, comments });
              }
            }}
          >
            Approve
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

