/**
 * SanityCheckDialog Component
 *
 * Modal dialog that shows sanity check progress and results.
 * Automatically triggered when user clicks Continue to next step.
 */

import {
  AlertCircle,
  CheckCircle,
  Loader2,
  AlertTriangle,
  ChevronRight,
  XCircle,
} from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import type { SanityCheckResult } from '../hooks/useSanityCheck';

interface SanityCheckDialogProps {
  /** Whether the dialog is open */
  open: boolean;
  /** Called when dialog should close */
  onOpenChange: (open: boolean) => void;
  /** Whether the check is currently running */
  isChecking: boolean;
  /** Error message if check failed */
  error: string | null;
  /** Results of the sanity check */
  result: SanityCheckResult | null;
  /** Called when user wants to proceed despite issues */
  onProceed: () => void;
  /** Called when user wants to go back and fix issues */
  onGoBack: () => void;
  /** Called to refresh/re-run the sanity check */
  onRefresh?: () => void;
  /** Called to scroll to a specific product */
  onScrollToProduct?: (productIndex: number) => void;
  /** Product names for display (indexed by product index) */
  productNames?: Record<number, string>;
  /** Number of validation errors (required fields, etc.) */
  validationErrorCount?: number;
}

export function SanityCheckDialog({
  open,
  onOpenChange,
  isChecking,
  error,
  result,
  onProceed,
  onGoBack,
  onScrollToProduct,
  productNames = {},
  validationErrorCount = 0
}: SanityCheckDialogProps) {
  const hasSanityIssues = result?.issues && result.issues.length > 0;
  const hasValidationErrors = validationErrorCount > 0;
  const hasAnyIssues = hasSanityIssues || hasValidationErrors;
  const allClear = !isChecking && !error && !hasSanityIssues && result;

  // Group issues by field, then by exact issue+suggestion combination for deduplication
  const issuesByField = result?.issues?.reduce((acc, issue) => {
    const field = issue.field;
    if (!acc[field]) {
      acc[field] = {};
    }

    const key = `${issue.issue}:${issue.suggestion || ''}`;
    if (!acc[field][key]) {
      acc[field][key] = {
        field: issue.field,
        issue: issue.issue,
        suggestion: issue.suggestion,
        productIndices: []
      };
    }
    acc[field][key].productIndices.push(issue.productIndex);
    return acc;
  }, {} as Record<string, Record<string, { field: string; issue: string; suggestion?: string; productIndices: number[] }>>) || {};

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <div className="flex items-center justify-between">
            <DialogTitle className="flex items-center gap-2">
              {isChecking ? (
                <>
                  Running Consistency Check...
                </>
              ) : error ? (
                <>
                  <XCircle className="h-5 w-5 text-red-500" />
                  Consistency Check Failed
                </>
              ) : hasAnyIssues ? (
                <>
                  <AlertTriangle className="h-5 w-5 text-amber-500" />
                  {hasValidationErrors && hasSanityIssues
                    ? 'Validation Errors & Consistency Issues Found'
                    : hasValidationErrors
                    ? 'Validation Errors'
                    : 'Consistency Issues Found'}
                </>
              ) : allClear ? (
                <>
                  Continue
                </>
              ) : (
                <>
                  <CheckCircle className="h-5 w-5 text-green-500" />
                  Consistency Check
                </>
              )}
            </DialogTitle>

          </div>
        </DialogHeader>

        {/* Content */}
        <div className="py-4">
          {/* Loading state */}
          {isChecking && (
            <div className="flex flex-col items-center justify-center py-8 gap-4">
              <Loader2 className="h-8 w-8 animate-spin text-purple-500" />
              <p className="text-sm text-muted-foreground">
                Analyzing {result?.totalProducts || '...'} products...
              </p>
            </div>
          )}

          {/* Error state */}
          {error && !isChecking && (
            <div className="flex items-start gap-3 p-4 rounded-lg bg-red-50 border border-red-200">
              <AlertCircle className="h-5 w-5 text-red-500 flex-shrink-0 mt-0.5" />
              <div>
                <p className="font-medium text-red-800">Error</p>
                <p className="text-sm text-red-600 mt-1">{error}</p>
              </div>
            </div>
          )}

          {/* Success state - only show if no validation errors either */}
          {allClear && !hasValidationErrors && !isChecking && (
            <div className="flex items-start gap-3 p-4 rounded-lg bg-green-50 border border-green-200">
              <div>
                <p className="text-sm text-green-600 mt-1">
                  {result?.summary || 'No consistency issues detected in your products.'}
                </p>
              </div>
            </div>
          )}

          {/* Validation errors warning */}
          {hasValidationErrors && !isChecking && (
            <div className="flex items-start gap-3 p-4 rounded-lg bg-red-50 border border-red-200 mb-2">
              <div>
                <p className="text-sm text-red-600">
                  There {validationErrorCount === 1 ? 'is' : 'are'} {validationErrorCount} validation error{validationErrorCount === 1 ? '' : 's'} (required fields missing, invalid values, etc.) in your data.
                  These should be fixed before continuing.
                </p>
              </div>
            </div>
          )}
          {hasSanityIssues && !isChecking && (
            <>
             {/* Summary */}
             {result?.summary && (
                  <div className="flex items-start gap-3 p-4 rounded-lg bg-amber-50 border border-amber-200">
                    <div>
                      <p className="text-sm text-amber-800">{result.summary}</p>
                    </div>
                  </div>
                )}
                </>
                )}

          {/* Sanity check issues list */}
          {hasSanityIssues && !isChecking && (
            <ScrollArea className="max-h-[400px] overflow-y-auto mt-4">
              <div className="space-y-4">
             

                {/* Issues grouped by field, then by unique issue+suggestion */}
                {Object.entries(issuesByField).map(([field, groups]) => (
                  <div key={field} className="space-y-2">
                    <div className="flex items-center gap-2">
                      <Badge variant="outline" className="text-xs font-semibold">
                        {formatFieldName(field)}
                      </Badge>
                      <span className="text-xs text-muted-foreground">
                        {Object.values(groups).reduce((sum, g) => sum + g.productIndices.length, 0)} issue{Object.values(groups).reduce((sum, g) => sum + g.productIndices.length, 0) === 1 ? '' : 's'}
                      </span>
                    </div>

                    {Object.entries(groups).map(([key, group]) => (
                      <div
                        key={key}
                        className="flex items-start gap-3 p-3 rounded-lg bg-gray-50 border border-gray-200 hover:border-gray-300 transition-colors"
                      >
                        <AlertCircle className="h-4 w-4 text-amber-500 flex-shrink-0 mt-0.5" />
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-2">
                            <span className="text-xs text-muted-foreground">
                              {group.productIndices.length} product{group.productIndices.length === 1 ? '' : 's'}
                            </span>
                          </div>
                          <div className="flex flex-wrap items-center gap-x-1 gap-y-1 mb-2">
                            {group.productIndices.map((productIndex, idx) => (
                              <span key={productIndex} className="inline-flex items-center">
                                <span className="text-sm font-medium">
                                  {productNames[productIndex] || `Product ${productIndex + 1}`}
                                </span>
                                {onScrollToProduct && (
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    className="h-5 px-1 text-xs text-blue-600 hover:text-blue-800"
                                    onClick={() => {
                                      onOpenChange(false);
                                      onScrollToProduct(productIndex);
                                    }}
                                  >
                                    <ChevronRight className="h-3 w-3" />
                                  </Button>
                                )}
                                {idx < group.productIndices.length - 1 && (
                                  <span className="text-gray-400 mr-1">,</span>
                                )}
                              </span>
                            ))}
                          </div>
                          <p className="text-sm text-gray-600">{group.issue}</p>
                          {group.suggestion && (
                            <p className="text-xs text-blue-600 mt-1">
                              {group.suggestion}
                            </p>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                ))}
              </div>
            </ScrollArea>
          )}
        </div>

        {/* Footer */}
        <DialogFooter>
          {isChecking ? (
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
          ) : error ? (
            <>
              <Button variant="outline" onClick={onGoBack}>
                Go Back
              </Button>
              <Button onClick={() => onOpenChange(false)}>
                Close
              </Button>
            </>
          ) : allClear && !hasValidationErrors ? (
            <Button onClick={onProceed}>
              Continue to Next Step
              <ChevronRight className="h-4 w-4 ml-1" />
            </Button>
          ) : hasAnyIssues ? (
            <>
              <Button variant="outline" onClick={onGoBack}>
                Go Back & Fix
              </Button>
              <Button onClick={onProceed} variant={hasValidationErrors ? 'destructive' : 'default'}>
                Proceed Anyway
              </Button>
            </>
          ) : null}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

/**
 * Format a field key into a human-readable name
 */
function formatFieldName(field: string): string {
  const fieldNames: Record<string, string> = {
    supplier_no: 'Supplier #',
    msrp: 'MSRP',
    cost_each: 'Cost Each',
    qty_per_unit: 'Min Qty',
    case_qty: 'Case Pack',
    tax_cat: 'Tax Category',
    size_cat: 'Size Category',
    name: 'Name',
    themes: 'Themes',
    weight: 'Weight',
    length: 'Length',
    width: 'Width',
    height: 'Height'
  };

  return fieldNames[field] || field.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
}