'use client';

import React, { useState, useCallback, useRef } from 'react';
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '@alga-psa/ui/components/Card';
import { Button } from '@alga-psa/ui/components/Button';
import { StringDateRangePicker } from '@alga-psa/ui/components/DateRangePicker';
import { Label } from '@alga-psa/ui/components/Label';
import { Upload, FileText, AlertCircle, CheckCircle2, HelpCircle, ChevronDown, ChevronUp } from 'lucide-react';
import { Alert, AlertDescription } from '@alga-psa/ui/components/Alert';
import { CSVImportPreview } from './CSVImportPreview';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';

interface CSVTaxImportPanelProps {
  onImportComplete?: (result: { importId: string; invoiceCount: number }) => void;
}

interface ValidationResult {
  valid: boolean;
  structureValid: boolean;
  rowsValid: boolean;
  databaseValid: boolean;
  errors: Array<{ rowNumber?: number; field: string; message: string }>;
  warnings: Array<{ rowNumber?: number; field: string; message: string }>;
  stats: {
    totalRows: number;
    validRows: number;
    matchedInvoices: number;
    uniqueInvoices: number;
    duplicateInvoices: string[];
  };
}

interface ImportResult {
  success: boolean;
  importId?: string;
  validation: ValidationResult;
  summary: {
    totalInvoices: number;
    successfulUpdates: number;
    failedUpdates: number;
    totalOriginalTax: number;
    totalImportedTax: number;
    totalDifference: number;
  };
  error?: string;
}

export function CSVTaxImportPanel({ onImportComplete }: CSVTaxImportPanelProps) {
  const { t } = useTranslation('msp/integrations');
  const [file, setFile] = useState<File | null>(null);
  const [dateRange, setDateRange] = useState<{ from: string; to: string }>({
    from: '',
    to: ''
  });
  const [isValidating, setIsValidating] = useState(false);
  const [isImporting, setIsImporting] = useState(false);
  const [validationResult, setValidationResult] = useState<ValidationResult | null>(null);
  const [importResult, setImportResult] = useState<ImportResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [showHelp, setShowHelp] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile) {
      setFile(selectedFile);
      setValidationResult(null);
      setImportResult(null);
      setError(null);
    }
  }, []);

  const handleDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    const droppedFile = e.dataTransfer.files?.[0];
    if (droppedFile && droppedFile.type === 'text/csv') {
      setFile(droppedFile);
      setValidationResult(null);
      setImportResult(null);
      setError(null);
    }
  }, []);

  const handleValidate = useCallback(async () => {
    if (!file || !dateRange.from || !dateRange.to) {
      setError(t('integrations.csv.taxImport.errors.selectFileAndRange', { defaultValue: 'Please select a file and date range' }));
      return;
    }

    setIsValidating(true);
    setError(null);

    try {
      const csvContent = await file.text();

      const response = await fetch('/api/accounting/csv/import/tax', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          csvContent,
          startDate: dateRange.from,
          endDate: dateRange.to,
          dryRun: true
        })
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(t('integrations.csv.taxImport.errors.validationFailed', { defaultValue: 'Validation failed' }));
      }

      setValidationResult(result.validation);
    } catch (err) {
      setError(t('integrations.csv.taxImport.errors.validationFailed', { defaultValue: 'Validation failed' }));
    } finally {
      setIsValidating(false);
    }
  }, [file, dateRange, t]);

  const handleImport = useCallback(async () => {
    if (!file || !dateRange.from || !dateRange.to) {
      setError(t('integrations.csv.taxImport.errors.selectFileAndRange', { defaultValue: 'Please select a file and date range' }));
      return;
    }

    setIsImporting(true);
    setError(null);

    try {
      const csvContent = await file.text();

      const response = await fetch('/api/accounting/csv/import/tax', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          csvContent,
          startDate: dateRange.from,
          endDate: dateRange.to,
          dryRun: false
        })
      });

      const result: ImportResult = await response.json();

      if (!response.ok) {
        throw new Error(t('integrations.csv.taxImport.errors.importFailed', { defaultValue: 'Import failed' }));
      }

      setImportResult(result);

      if (result.success && result.importId) {
        onImportComplete?.({
          importId: result.importId,
          invoiceCount: result.summary.successfulUpdates
        });
      }
    } catch (err) {
      setError(t('integrations.csv.taxImport.errors.importFailed', { defaultValue: 'Import failed' }));
    } finally {
      setIsImporting(false);
    }
  }, [file, dateRange, onImportComplete, t]);

  const handleDownloadTemplate = useCallback(async () => {
    try {
      const response = await fetch('/api/accounting/csv/import/tax/template');
      if (!response.ok) {
        throw new Error(t('integrations.csv.taxImport.errors.templateDownloadFailed', { defaultValue: 'Failed to download template' }));
      }
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'tax-import-template.csv';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (err) {
      setError(t('integrations.csv.taxImport.errors.templateDownloadFailed', { defaultValue: 'Failed to download template' }));
    }
  }, [t]);

  const canValidate = file && dateRange.from && dateRange.to;
  const canImport = validationResult?.valid && !isValidating;

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Upload className="h-5 w-5" />
          {t('integrations.csv.taxImport.qbo.title', { defaultValue: 'Import Tax from QuickBooks CSV' })}
        </CardTitle>
        <CardDescription>
          {t('integrations.csv.taxImport.qbo.description', { defaultValue: 'Import tax amounts from a QuickBooks tax report CSV file.' })}
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Help Section */}
        <div className="border rounded-lg">
          <button
            type="button"
            onClick={() => setShowHelp(!showHelp)}
            className="flex items-center justify-between w-full p-4 text-left hover:bg-muted/50"
          >
            <div className="flex items-center gap-2">
              <HelpCircle className="h-5 w-5 text-blue-500" />
              <span className="font-medium">{t('integrations.csv.taxImport.qbo.help.title', { defaultValue: 'How to export tax data from QuickBooks' })}</span>
            </div>
            {showHelp ? (
              <ChevronUp className="h-5 w-5 text-muted-foreground" />
            ) : (
              <ChevronDown className="h-5 w-5 text-muted-foreground" />
            )}
          </button>
          {showHelp && (
            <div className="px-4 pb-4 space-y-3 text-sm text-muted-foreground">
              <ol className="list-decimal list-inside space-y-2">
                <li>{t('integrations.csv.taxImport.qbo.help.steps.s1', { defaultValue: 'In QuickBooks, go to Reports > All Reports' })}</li>
                <li>{t('integrations.csv.taxImport.qbo.help.steps.s2', { defaultValue: 'Select Sales Tax Liability or Transaction Detail by Account' })}</li>
                <li>{t('integrations.csv.taxImport.qbo.help.steps.s3', { defaultValue: 'Set the date range to match your exported invoices' })}</li>
                <li>{t('integrations.csv.taxImport.qbo.help.steps.s4', { defaultValue: 'Click Export and choose Export to Excel or Export to CSV' })}</li>
                <li>{t('integrations.csv.taxImport.qbo.help.steps.s5', { defaultValue: 'Save the file and upload it here' })}</li>
              </ol>
              <p className="text-muted-foreground">
                {t('integrations.csv.taxImport.qbo.help.csvRequirement', { defaultValue: 'The CSV must include Invoice Number, Invoice Date, and Tax Amount columns.' })}
              </p>
              <button
                type="button"
                onClick={handleDownloadTemplate}
                className="text-blue-600 hover:underline"
              >
                {t('integrations.csv.taxImport.qbo.help.downloadTemplate', { defaultValue: 'Download template CSV' })}
              </button>
            </div>
          )}
        </div>

        {/* Date Range (Required) */}
        <div>
          <StringDateRangePicker
            id="csv-tax-import-date-range"
            label={t('integrations.csv.taxImport.fields.dateRangeRequired', { defaultValue: 'Date Range (required)' })}
            value={dateRange}
            onChange={setDateRange}
          />
          <p className="text-sm text-muted-foreground mt-1">
            {t('integrations.csv.taxImport.fields.dateRangeHelp', { defaultValue: 'Only invoices within this date range will be processed.' })}
          </p>
        </div>

        {/* File Upload */}
        <div className="space-y-2">
          <Label>{t('integrations.csv.taxImport.fields.csvFile', { defaultValue: 'CSV File' })}</Label>
          <div
            onDrop={handleDrop}
            onDragOver={(e) => e.preventDefault()}
            onClick={() => fileInputRef.current?.click()}
            className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${
              file ? 'border-green-400 bg-green-50 dark:bg-green-950/30 dark:border-green-600' : 'border-border hover:border-muted-foreground hover:bg-muted/50'
            }`}
          >
            <input
              ref={fileInputRef}
              type="file"
              accept=".csv"
              onChange={handleFileSelect}
              className="hidden"
            />
            {file ? (
              <div className="flex items-center justify-center gap-2 text-green-700">
                <FileText className="h-6 w-6" />
                <span className="font-medium">{file.name}</span>
                <span className="text-sm text-muted-foreground">
                  {t('integrations.csv.taxImport.fields.fileSize', { defaultValue: '({{size}} KB)', size: (file.size / 1024).toFixed(1) })}
                </span>
              </div>
            ) : (
              <div className="text-muted-foreground">
                <Upload className="h-8 w-8 mx-auto mb-2" />
                <p>{t('integrations.csv.taxImport.fields.dropZone', { defaultValue: 'Drag and drop a CSV file here, or click to browse' })}</p>
              </div>
            )}
          </div>
        </div>

        {/* Error Message */}
        {error && (
          <Alert variant="destructive">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        {/* Validation/Import Preview */}
        {validationResult && (
          <CSVImportPreview validation={validationResult} importResult={importResult} />
        )}

        {/* Success Message */}
        {importResult?.success && (
          <Alert variant="success">
            <AlertDescription>
              {importResult.summary.successfulUpdates === 1
                ? t('integrations.csv.taxImport.qbo.success.one', { defaultValue: 'Successfully imported tax for {{count}} invoice. Total tax imported: ${{amount}}', count: importResult.summary.successfulUpdates, amount: (importResult.summary.totalImportedTax / 100).toFixed(2) })
                : t('integrations.csv.taxImport.qbo.success.other', { defaultValue: 'Successfully imported tax for {{count}} invoices. Total tax imported: ${{amount}}', count: importResult.summary.successfulUpdates, amount: (importResult.summary.totalImportedTax / 100).toFixed(2) })}
            </AlertDescription>
          </Alert>
        )}

        {/* Action Buttons */}
        <div className="flex justify-end gap-3">
          <Button
            id="csv-validate-button"
            variant="outline"
            onClick={handleValidate}
            disabled={!canValidate || isValidating || isImporting}
          >
            {isValidating ? (
              <>
                <span className="animate-spin mr-2">⏳</span>
                {t('integrations.csv.taxImport.actions.validating', { defaultValue: 'Validating...' })}
              </>
            ) : (
              t('integrations.csv.taxImport.actions.validate', { defaultValue: 'Validate' })
            )}
          </Button>
          <Button
            id="csv-import-button"
            onClick={handleImport}
            disabled={!canImport || isImporting}
          >
            {isImporting ? (
              <>
                <span className="animate-spin mr-2">⏳</span>
                {t('integrations.csv.taxImport.actions.importing', { defaultValue: 'Importing...' })}
              </>
            ) : (
              <>
                <Upload className="h-4 w-4 mr-2" />
                {t('integrations.csv.taxImport.actions.importTaxData', { defaultValue: 'Import Tax Data' })}
              </>
            )}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
