/**
 * @ai-summary Modal for reviewing and editing OCR-extracted receipt fields
 * @ai-context Shows extracted fields with confidence indicators and allows editing before accepting
 */

import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Typography,
  TextField,
  Grid,
  useTheme,
  useMediaQuery,
  IconButton,
  Collapse,
  Alert,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import CheckIcon from '@mui/icons-material/Check';
import CloseIcon from '@mui/icons-material/Close';
import CameraAltIcon from '@mui/icons-material/CameraAlt';
import {
  ExtractedReceiptFields,
  ExtractedReceiptField,
  LOW_CONFIDENCE_THRESHOLD,
} from '../hooks/useReceiptOcr';
import { ReceiptPreview } from './ReceiptPreview';

export interface ReceiptOcrReviewModalProps {
  /** Whether the modal is open */
  open: boolean;
  /** Extracted fields from OCR */
  extractedFields: ExtractedReceiptFields;
  /** Receipt image URL for preview */
  receiptImageUrl: string | null;
  /** Called when user accepts the fields */
  onAccept: () => void;
  /** Called when user wants to retake the photo */
  onRetake: () => void;
  /** Called when user cancels */
  onCancel: () => void;
  /** Called when user edits a field */
  onFieldEdit: (fieldName: keyof ExtractedReceiptFields, value: string | number | null) => void;
}

/** Confidence indicator component */
const ConfidenceIndicator: React.FC<{ confidence: number }> = ({ confidence }) => {
  const filledDots = Math.round(confidence * 4);
  const isLow = confidence < LOW_CONFIDENCE_THRESHOLD;

  return (
    <Box
      sx={{
        display: 'flex',
        gap: 0.25,
        ml: 1,
      }}
      aria-label={`Confidence: ${Math.round(confidence * 100)}%`}
    >
      {[0, 1, 2, 3].map((i) => (
        <Box
          key={i}
          sx={{
            width: 6,
            height: 6,
            borderRadius: '50%',
            backgroundColor: i < filledDots
              ? (isLow ? 'warning.main' : 'success.main')
              : 'grey.300',
          }}
        />
      ))}
    </Box>
  );
};

/** Field row component with inline editing */
const FieldRow: React.FC<{
  label: string;
  field: ExtractedReceiptField;
  onEdit: (value: string | number | null) => void;
  type?: 'text' | 'number' | 'date';
  formatDisplay?: (value: string | number | null) => string;
}> = ({ label, field, onEdit, type = 'text', formatDisplay }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editValue, setEditValue] = useState<string>(
    field.value !== null ? String(field.value) : ''
  );
  const isLowConfidence = field.confidence < LOW_CONFIDENCE_THRESHOLD && field.value !== null;

  const displayValue = formatDisplay
    ? formatDisplay(field.value)
    : field.value !== null
      ? String(field.value)
      : '-';

  const handleSave = () => {
    let parsedValue: string | number | null = editValue || null;

    if (type === 'number' && editValue) {
      const num = parseFloat(editValue);
      parsedValue = isNaN(num) ? null : num;
    }

    onEdit(parsedValue);
    setIsEditing(false);
  };

  const handleCancel = () => {
    setEditValue(field.value !== null ? String(field.value) : '');
    setIsEditing(false);
  };

  return (
    <Box
      sx={{
        display: 'flex',
        alignItems: 'center',
        py: 1.5,
        px: 1,
        borderRadius: 1,
        backgroundColor: isLowConfidence ? 'warning.light' : 'transparent',
        '&:hover': {
          backgroundColor: isLowConfidence ? 'warning.light' : 'action.hover',
        },
      }}
    >
      <Typography
        variant="body2"
        sx={{
          width: 100,
          flexShrink: 0,
          color: 'text.secondary',
          fontWeight: 500,
        }}
      >
        {label}
      </Typography>

      {isEditing ? (
        <Box sx={{ display: 'flex', alignItems: 'center', flex: 1, gap: 1 }}>
          <TextField
            size="small"
            value={editValue}
            onChange={(e) => setEditValue(e.target.value)}
            type={type === 'number' ? 'number' : 'text'}
            inputProps={{
              step: type === 'number' ? 0.001 : undefined,
            }}
            autoFocus
            sx={{ flex: 1 }}
            onKeyDown={(e) => {
              if (e.key === 'Enter') handleSave();
              if (e.key === 'Escape') handleCancel();
            }}
          />
          <IconButton size="small" onClick={handleSave} color="primary">
            <CheckIcon fontSize="small" />
          </IconButton>
          <IconButton size="small" onClick={handleCancel}>
            <CloseIcon fontSize="small" />
          </IconButton>
        </Box>
      ) : (
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            flex: 1,
            cursor: 'pointer',
          }}
          onClick={() => setIsEditing(true)}
          role="button"
          tabIndex={0}
          aria-label={`Edit ${label}`}
          onKeyDown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault();
              setIsEditing(true);
            }
          }}
        >
          <Typography
            variant="body1"
            sx={{
              flex: 1,
              fontWeight: field.value !== null ? 500 : 400,
              color: field.value !== null ? 'text.primary' : 'text.disabled',
            }}
          >
            {displayValue}
          </Typography>
          {field.value !== null && <ConfidenceIndicator confidence={field.confidence} />}
          <IconButton size="small" sx={{ ml: 1 }}>
            <EditIcon fontSize="small" />
          </IconButton>
        </Box>
      )}
    </Box>
  );
};

export const ReceiptOcrReviewModal: React.FC<ReceiptOcrReviewModalProps> = ({
  open,
  extractedFields,
  receiptImageUrl,
  onAccept,
  onRetake,
  onCancel,
  onFieldEdit,
}) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const [showAllFields, setShowAllFields] = useState(false);

  // Check if any fields have low confidence
  const hasLowConfidenceFields = Object.values(extractedFields).some(
    (field) => field.value !== null && field.confidence < LOW_CONFIDENCE_THRESHOLD
  );

  // Format currency display
  const formatCurrency = (value: string | number | null): string => {
    if (value === null) return '-';
    const num = typeof value === 'string' ? parseFloat(value) : value;
    return isNaN(num) ? String(value) : `$${num.toFixed(2)}`;
  };

  // Format date display
  const formatDate = (value: string | number | null): string => {
    if (value === null) return '-';
    const dateStr = String(value);
    try {
      const date = new Date(dateStr);
      if (!isNaN(date.getTime())) {
        return date.toLocaleDateString('en-US', {
          month: 'short',
          day: 'numeric',
          year: 'numeric',
        });
      }
    } catch {
      // Return as-is if parsing fails
    }
    return dateStr;
  };

  return (
    <Dialog
      open={open}
      onClose={onCancel}
      maxWidth="sm"
      fullWidth
      fullScreen={isMobile}
      PaperProps={{
        sx: {
          maxHeight: isMobile ? '100vh' : '90vh',
        },
      }}
    >
      <DialogTitle
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <Typography variant="h6" component="span">
          Receipt Data Extracted
        </Typography>
        <IconButton onClick={onCancel} size="small" aria-label="Close">
          <CloseIcon />
        </IconButton>
      </DialogTitle>

      <DialogContent dividers>
        {hasLowConfidenceFields && (
          <Alert severity="warning" sx={{ mb: 2 }}>
            Some fields have low confidence. Please review and edit if needed.
          </Alert>
        )}

        <Grid container spacing={2}>
          {/* Receipt thumbnail */}
          {receiptImageUrl && (
            <Grid item xs={12} sm={4}>
              <Box
                sx={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 1,
                }}
              >
                <ReceiptPreview
                  imageUrl={receiptImageUrl}
                  maxWidth={isMobile ? 100 : 120}
                  maxHeight={isMobile ? 150 : 180}
                />
                <Typography variant="caption" color="text.secondary">
                  Tap to zoom
                </Typography>
              </Box>
            </Grid>
          )}

          {/* Extracted fields */}
          <Grid item xs={12} sm={receiptImageUrl ? 8 : 12}>
            <Box sx={{ display: 'flex', flexDirection: 'column' }}>
              {/* Primary fields */}
              <FieldRow
                label="Date"
                field={extractedFields.transactionDate}
                onEdit={(value) => onFieldEdit('transactionDate', value)}
                type="text"
                formatDisplay={formatDate}
              />
              <FieldRow
                label="Gallons"
                field={extractedFields.fuelQuantity}
                onEdit={(value) => onFieldEdit('fuelQuantity', value)}
                type="number"
              />
              <FieldRow
                label="$/Gallon"
                field={extractedFields.pricePerUnit}
                onEdit={(value) => onFieldEdit('pricePerUnit', value)}
                type="number"
                formatDisplay={formatCurrency}
              />
              <FieldRow
                label="Total"
                field={extractedFields.totalAmount}
                onEdit={(value) => onFieldEdit('totalAmount', value)}
                type="number"
                formatDisplay={formatCurrency}
              />

              {/* Secondary fields (collapsible on mobile) */}
              <Collapse in={!isMobile || showAllFields}>
                <FieldRow
                  label="Grade"
                  field={extractedFields.fuelGrade}
                  onEdit={(value) => onFieldEdit('fuelGrade', value)}
                  type="text"
                />
                <FieldRow
                  label="Station"
                  field={extractedFields.merchantName}
                  onEdit={(value) => onFieldEdit('merchantName', value)}
                  type="text"
                />
              </Collapse>

              {isMobile && (
                <Button
                  size="small"
                  onClick={() => setShowAllFields(!showAllFields)}
                  sx={{ mt: 1, alignSelf: 'flex-start' }}
                >
                  {showAllFields ? 'Show Less' : 'Show More Fields'}
                </Button>
              )}
            </Box>
          </Grid>
        </Grid>

        <Typography
          variant="body2"
          color="text.secondary"
          sx={{ mt: 2, textAlign: 'center' }}
        >
          Tap any field to edit before saving.
        </Typography>
      </DialogContent>

      <DialogActions
        sx={{
          flexDirection: isMobile ? 'column' : 'row',
          gap: 1,
          p: 2,
        }}
      >
        <Button
          onClick={onRetake}
          startIcon={<CameraAltIcon />}
          sx={{ order: isMobile ? 2 : 1 }}
        >
          Retake Photo
        </Button>
        <Box sx={{ flex: 1, display: isMobile ? 'none' : 'block' }} />
        <Button
          onClick={onCancel}
          sx={{ order: isMobile ? 3 : 2 }}
        >
          Cancel
        </Button>
        <Button
          variant="contained"
          onClick={onAccept}
          startIcon={<CheckIcon />}
          sx={{ order: isMobile ? 1 : 3, width: isMobile ? '100%' : 'auto' }}
        >
          Accept
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default ReceiptOcrReviewModal;
