/**
 * Document Assembly Component
 * UI for template-based document generation
 */

import React, { useState } from 'react';
import { useQuery, useMutation } from '@tanstack/react-query';
import {
  Box,
  Button,
  Card,
  CardContent,
  Stepper,
  Step,
  StepLabel,
  TextField,
  Typography,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  Chip,
} from '@mui/material';
import { CheckCircle as CheckCircleIcon } from '@mui/icons-material';

interface Template {
  id: string;
  name: string;
  variables?: string[];
}

export function DocumentAssembly() {
  const [activeStep, setActiveStep] = useState(0);
  const [selectedTemplate, setSelectedTemplate] = useState<string>('');
  const [variables, setVariables] = useState<Record<string, string>>({});
  const [preview, setPreview] = useState<string>('');

  const { data: templates } = useQuery<Template[]>({
    queryKey: ['templates'],
    queryFn: async () => {
      const response = await fetch('/api/templates');
      const data = await response.json();
      return data.templates || [];
    },
  });

  const previewMutation = useMutation({
    mutationFn: async ({ templateId, vars }: { templateId: string; vars: Record<string, string> }) => {
      const response = await fetch(`/api/templates/${templateId}/render`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ variables: vars }),
      });
      return response.json();
    },
    onSuccess: (data) => {
      setPreview(data.rendered);
      setActiveStep(2);
    },
  });

  const generateMutation = useMutation({
    mutationFn: async (data: any) => {
      const response = await fetch('/api/assembly/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
      return response.json();
    },
    onSuccess: () => {
      setActiveStep(3);
    },
  });

  const handleNext = () => {
    if (activeStep === 0 && selectedTemplate) {
      // Get template variables
      fetch(`/api/templates/${selectedTemplate}/variables`)
        .then((res) => res.json())
        .then((data) => {
          const vars: Record<string, string> = {};
          data.variables?.forEach((v: string) => {
            vars[v] = '';
          });
          setVariables(vars);
          setActiveStep(1);
        });
    } else if (activeStep === 1) {
      previewMutation.mutate({ templateId: selectedTemplate, vars: variables });
    } else if (activeStep === 2) {
      generateMutation.mutate({
        template_id: selectedTemplate,
        variables,
        title: `Document from ${templates?.find((t) => t.id === selectedTemplate)?.name}`,
        save_document: true,
      });
    }
  };

  const steps = ['Select Template', 'Enter Variables', 'Preview', 'Complete'];

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        Document Assembly
      </Typography>

      <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
        {steps.map((label) => (
          <Step key={label}>
            <StepLabel>{label}</StepLabel>
          </Step>
        ))}
      </Stepper>

      {activeStep === 0 && (
        <Grid container spacing={3}>
          {templates?.map((template) => (
            <Grid item xs={12} sm={6} md={4} key={template.id}>
              <Card
                sx={{
                  cursor: 'pointer',
                  border: selectedTemplate === template.id ? 2 : 1,
                  borderColor: selectedTemplate === template.id ? 'primary.main' : 'divider',
                }}
                onClick={() => setSelectedTemplate(template.id)}
              >
                <CardContent>
                  <Typography variant="h6">{template.name}</Typography>
                </CardContent>
              </Card>
            </Grid>
          ))}
        </Grid>
      )}

      {activeStep === 1 && (
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Enter Variable Values
            </Typography>
            {Object.keys(variables).map((key) => (
              <TextField
                key={key}
                fullWidth
                label={key}
                value={variables[key]}
                onChange={(e) => setVariables({ ...variables, [key]: e.target.value })}
                margin="normal"
              />
            ))}
          </CardContent>
        </Card>
      )}

      {activeStep === 2 && (
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Preview
            </Typography>
            <Box
              sx={{
                p: 2,
                bgcolor: 'grey.100',
                borderRadius: 1,
                whiteSpace: 'pre-wrap',
                maxHeight: 400,
                overflow: 'auto',
              }}
            >
              {preview || 'Generating preview...'}
            </Box>
          </CardContent>
        </Card>
      )}

      {activeStep === 3 && (
        <Card>
          <CardContent sx={{ textAlign: 'center' }}>
            <CheckCircleIcon color="success" sx={{ fontSize: 64, mb: 2 }} />
            <Typography variant="h5" gutterBottom>
              Document Generated Successfully!
            </Typography>
            <Button variant="contained" href="/documents">
              View Documents
            </Button>
          </CardContent>
        </Card>
      )}

      <Box display="flex" justifyContent="space-between" mt={4}>
        <Button disabled={activeStep === 0} onClick={() => setActiveStep(activeStep - 1)}>
          Back
        </Button>
        {activeStep < 3 && (
          <Button variant="contained" onClick={handleNext} disabled={!selectedTemplate}>
            {activeStep === 2 ? 'Generate Document' : 'Next'}
          </Button>
        )}
      </Box>
    </Box>
  );
}

