'use client';

import { useState, useEffect, useCallback } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { format } from 'date-fns';
import { useToast } from '@/hooks/use-toast';
import { getImportById, calculateCintasSummaries } from '@/app/actions/imports';

interface CintasSummary {
  id: number;
  week: string;
  trrTotal: number;
  fourWkAverages: number;
  trrPlus4Wk: number;
  powerAdds: number;
  weekId: number;
  importId: number;
}

interface ImportDetail {
  id: number;
  name: string;
  importDate: Date;
  layout: {
    id: number;
    name: string;
    sections: Array<{
      id: number;
      name: string;
      tableName: string;
      fields: Array<{
        id: number;
        name: string;
        createdAt: Date;
        updatedAt: Date;
        layoutSectionId: number;
        cellPosition: string;
        dataType: string;
        dataTypeFormat: string | null;
        importTableColumnName: string;
        importColumnOrderNumber: number;
      }>;
    }>;
  };
  cintasSummaries: CintasSummary[];
  file?: {
    id: string;
    filename: string;
    size: number;
    contentType: string;
  };
}

interface ImportDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  importId: number;
}

export function ImportDetailDialog({ open, onOpenChange, importId }: ImportDetailDialogProps) {
  const [importDetail, setImportDetail] = useState<ImportDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [calculating, setCalculating] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [importStatus, setImportStatus] = useState<'idle' | 'processing' | 'completed' | 'failed'>('idle');
  const { toast } = useToast();

  const loadImportDetail = useCallback(async () => {
    try {
      const result = await getImportById(importId);
      if (result.success && result.data) {
        setImportDetail(result.data);
      } else {
        toast({
          title: 'Error',
          description: result.error || 'Failed to load import details',
          variant: 'destructive',
        });
        setImportDetail(null);
      }
    } catch {
      toast({
        title: 'Error',
        description: 'Failed to load import details',
        variant: 'destructive',
      });
      setImportDetail(null);
    } finally {
      setLoading(false);
    }
  }, [importId, toast]);

  useEffect(() => {
    if (open && importId) {
      loadImportDetail();
    }
  }, [open, importId, loadImportDetail]);

  async function handleCalculateSummaries() {
    setCalculating(true);
    try {
      const result = await calculateCintasSummaries(importId);
      if (result.success) {
        toast({
          title: 'Success',
          description: 'Cintas summaries calculated successfully',
        });
        loadImportDetail();
      } else {
        toast({
          title: 'Error',
          description: result.error || 'Failed to calculate summaries',
          variant: 'destructive',
        });
      }
    } catch {
      toast({
        title: 'Error',
        description: 'Failed to calculate summaries',
        variant: 'destructive',
      });
    } finally {
      setCalculating(false);
    }
  }

  async function handleTriggerImport() {
    if (!importDetail?.file) {
      toast({
        title: 'Error',
        description: 'No file attached to this import',
        variant: 'destructive',
      });
      return;
    }

    setProcessing(true);
    setImportStatus('processing');

    try {
      const response = await fetch(`/api/imports/${importId}/trigger`, {
        method: 'POST',
      });

      const result = await response.json();

      if (result.success) {
        toast({
          title: 'Success',
          description: 'Import process started successfully',
        });

        // Set up WebSocket connection for progress updates
        const ws = new WebSocket(`ws://localhost:3001/import-progress/${importId}`);

        ws.onmessage = (event) => {
          const progress = JSON.parse(event.data);

          if (progress.status === 'completed') {
            setImportStatus('completed');
            setProcessing(false);
            ws.close();
            toast({
              title: 'Import Complete',
              description: `Successfully imported ${progress.totalInserted || 0} rows`,
            });
          } else if (progress.status === 'failed') {
            setImportStatus('failed');
            setProcessing(false);
            ws.close();
            toast({
              title: 'Import Failed',
              description: progress.errors?.[0] || 'Import process failed',
              variant: 'destructive',
            });
          }
        };

        ws.onerror = () => {
          setProcessing(false);
          setImportStatus('failed');
          toast({
            title: 'Connection Error',
            description: 'Failed to connect to import progress server',
            variant: 'destructive',
          });
        };

      } else {
        toast({
          title: 'Error',
          description: result.error || 'Failed to start import process',
          variant: 'destructive',
        });
        setProcessing(false);
        setImportStatus('failed');
      }
    } catch {
      toast({
        title: 'Error',
        description: 'Failed to trigger import process',
        variant: 'destructive',
      });
      setProcessing(false);
      setImportStatus('failed');
    }
  }

  if (loading) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-4xl max-h-[80vh]">
          <DialogHeader>
            <DialogTitle>Loading Import Details</DialogTitle>
            <DialogDescription>
              Please wait while we load the import information...
            </DialogDescription>
          </DialogHeader>
          <div className="flex justify-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
          </div>
        </DialogContent>
      </Dialog>
    );
  }

  if (!importDetail) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Import Details</DialogTitle>
          <DialogDescription>
            View detailed information about this import
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Import Information</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <div className="flex justify-between">
                <span className="font-medium">Name:</span>
                <span>{importDetail.name}</span>
              </div>
              <div className="flex justify-between">
                <span className="font-medium">Layout:</span>
                <span>{importDetail.layout.name}</span>
              </div>
              <div className="flex justify-between">
                <span className="font-medium">Import Date:</span>
                <span>{format(importDetail.importDate, 'PPpp')}</span>
              </div>
              {importDetail.file && (
                <div className="flex justify-between">
                  <span className="font-medium">File:</span>
                  <span>{importDetail.file.filename}</span>
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Layout Configuration</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {importDetail.layout.sections.map((section) => (
                  <div key={section.id} className="border rounded-lg p-4">
                    <h4 className="font-medium mb-2">{section.name}</h4>
                    <p className="text-sm text-muted-foreground mb-2">
                      Table: {section.tableName}
                    </p>
                    <div className="grid gap-1">
                      {section.fields.map((field) => (
                        <div key={field.importTableColumnName} className="text-sm">
                          <span className="font-medium">{field.name}:</span>
                          <span className="ml-2 text-muted-foreground">
                            {field.importTableColumnName}
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <div className="flex justify-between items-center">
                <CardTitle>Import Actions</CardTitle>
                <div className="flex gap-2">
                  <Button
                    onClick={handleTriggerImport}
                    disabled={processing || !importDetail.file}
                    size="sm"
                    variant="default"
                  >
                    {processing ? 'Processing...' : 'Start Import'}
                  </Button>
                  <Button
                    onClick={handleCalculateSummaries}
                    disabled={calculating || processing}
                    size="sm"
                    variant="secondary"
                  >
                    {calculating ? 'Calculating...' : 'Calculate Summaries'}
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              {importStatus === 'processing' && (
                <div className="flex items-center gap-2 text-sm text-blue-600">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
                  Import is currently processing...
                </div>
              )}
              {importStatus === 'completed' && (
                <div className="text-sm text-green-600">
                  Import completed successfully!
                </div>
              )}
              {importStatus === 'failed' && (
                <div className="text-sm text-red-600">
                  Import failed. Please check the logs for details.
                </div>
              )}
              {!importDetail.file && (
                <div className="text-sm text-yellow-600">
                  No file attached. Please upload a file before starting import.
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Cintas Summaries</CardTitle>
            </CardHeader>
            <CardContent>
              {importDetail.cintasSummaries.length === 0 ? (
                <p className="text-muted-foreground">No summaries calculated yet</p>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b">
                        <th className="text-left py-2">Week</th>
                        <th className="text-right py-2">TRR Total</th>
                        <th className="text-right py-2">4WK Averages</th>
                        <th className="text-right py-2">TRR + 4WK</th>
                        <th className="text-right py-2">Power Adds</th>
                      </tr>
                    </thead>
                    <tbody>
                      {importDetail.cintasSummaries.map((summary) => (
                        <tr key={summary.id} className="border-b">
                          <td className="py-2">{summary.week}</td>
                          <td className="text-right py-2">{summary.trrTotal}</td>
                          <td className="text-right py-2">{summary.fourWkAverages}</td>
                          <td className="text-right py-2">{summary.trrPlus4Wk}</td>
                          <td className="text-right py-2">{summary.powerAdds}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        <div className="flex justify-end gap-2 mt-6">
          <Button onClick={() => onOpenChange(false)}>Close</Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}