'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Header from '@/components/Header';
import styles from './page.module.css';
import { useUser } from '@/lib/auth/UserContext';
import { useLocale } from '@/lib/i18n/LocaleContext';

interface ValidationError {
  row: number;
  column: string;
  value: any;
  code: string;
  metadata: any;
}

export default function SalesImportPage() {
  const router = useRouter();
  const { t } = useLocale();
  const [file, setFile] = useState<File | null>(null);
  const [dragActive, setDragActive] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [idempotencyKey, setIdempotencyKey] = useState('');
  const [successData, setSuccessData] = useState<{ count: number; totalAmount?: number } | null>(null);
  const [validationErrors, setValidationErrors] = useState<ValidationError[]>([]);
  const [generalError, setGeneralError] = useState<string | null>(null);
  const [statusMessage, setStatusMessage] = useState('');
  const { role, user: currentUser, isLoading: contextLoading } = useUser();

  const translate = (code: string, metadata: any = {}, value?: any) => {
    let template = t('import.errors.' + code);
    if (template === 'import.errors.' + code) {
      template = code; // Fallback
    }
    const merged = { ...metadata };
    if (value !== undefined) {
      merged.value = value;
    }
    for (const key of Object.keys(merged)) {
      template = template.replace(`{${key}}`, String(merged[key]));
    }
    return template;
  };

  useEffect(() => {
    if (!contextLoading) {
      if (!currentUser) {
        router.push('/login');
        return;
      }
      const allowed = ['admin', 'analyst', 'commercial_leader'];
      if (!allowed.includes(role || '')) {
        router.push('/unauthorized');
        return;
      }
    }
  }, [contextLoading, currentUser, role, router]);

  useEffect(() => {
    const key = 'key-' + Date.now() + '-' + Math.random().toString(36).substring(2, 9);
    setIdempotencyKey(key);
  }, []);

  if (contextLoading) {
    return (
      <div className={styles.container}>
        <Header activeTab="import" />
        <main className={styles.main}>
          <div className={styles.card} style={{ textAlign: 'center', padding: '2rem' }}>
            <p>{t('import.loading')}</p>
          </div>
        </main>
      </div>
    );
  }

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      const droppedFile = e.dataTransfer.files[0];
      if (droppedFile.name.endsWith('.xlsx') || droppedFile.name.endsWith('.xls') || droppedFile.name.endsWith('.csv')) {
        setFile(droppedFile);
        setGeneralError(null);
        setValidationErrors([]);
        setSuccessData(null);
      } else {
        setGeneralError(t('import.unsupportedFile'));
      }
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const selectedFile = e.target.files[0];
      setFile(selectedFile);
      setGeneralError(null);
      setValidationErrors([]);
      setSuccessData(null);
    }
  };

  const startPolling = (key: string) => {
    setStatusMessage(t('import.statusPolling'));
    const interval = setInterval(async () => {
      try {
        const res = await fetch(`/api/sales/import/status/${key}`);
        if (res.ok) {
          const data = await res.json();
          if (data.metadata?.status === 'SUCCESS') {
            clearInterval(interval);
            setIsUploading(false);
            setProgress(100);
            setSuccessData({ count: data.metadata.count || 0 });
            setStatusMessage('');
          } else if (data.metadata?.status === 'FAILED') {
            clearInterval(interval);
            setIsUploading(false);
            setProgress(0);
            setGeneralError(data.metadata.errorMessage || "Fallo en el procesamiento de n8n.");
            setStatusMessage('');
          }
        }
      } catch (err) {
        console.error('Polling status error:', err);
      }
    }, 2000);

    setTimeout(() => {
      clearInterval(interval);
      if (isUploading) {
        setIsUploading(false);
        setGeneralError(t('import.timeout'));
      }
    }, 30000);
  };

  const handleUpload = async () => {
    if (!file || !idempotencyKey) return;

    setIsUploading(true);
    setProgress(10);
    setGeneralError(null);
    setValidationErrors([]);
    setSuccessData(null);

    const formData = new FormData();
    formData.append('file', file);

    try {
      setProgress(40);
      const res = await fetch('/api/sales/import', {
        method: 'POST',
        headers: {
          'idempotency-key': idempotencyKey
        },
        body: formData
      });

      setProgress(80);
      const data = await res.json();

      if (res.status === 201) {
        setProgress(100);
        setIsUploading(false);
        setSuccessData(data.metadata || { count: 0 });
      } else if (res.status === 202) {
        setProgress(90);
        startPolling(idempotencyKey);
      } else if (res.status === 200 && data.code === 'IMPORT_ALREADY_PROCESSED') {
        setProgress(100);
        setIsUploading(false);
        setSuccessData(data.metadata);
        setGeneralError(translate(data.code, data.metadata));
      } else {
        setIsUploading(false);
        setProgress(0);
        if (data.error?.code === 'IMPORT_VALIDATION_FAILED') {
          setValidationErrors(data.error.details || []);
          setGeneralError(translate(data.error.code));
        } else {
          setGeneralError(translate(data.error?.code || 'INTERNAL_SERVER_ERROR', data.error?.metadata));
        }
      }

    } catch (err: any) {
      setIsUploading(false);
      setProgress(0);
      setGeneralError(t('import.networkError'));
    }
  };

  return (
    <div className={styles.container}>
      <Header activeTab="import" />
      <main className={styles.main}>
        <div className={styles.card}>
          <div className={styles.header}>
            <h1 className={styles.title}>{t('import.title')}</h1>
            <p className={styles.subtitle}>{t('import.subtitle')}</p>
          </div>

          <div className={styles.templateDownload}>
            <span className={styles.templateLabel}>{t('import.templateLabel')}</span>
            <a 
              href="/templates/import_sales_template.xlsx" 
              download="import_sales_template.xlsx" 
              className={styles.downloadBtn}
              id="btn-download-template"
            >
              {t('import.downloadTemplate')}
            </a>
          </div>

          <div 
            className={`${styles.dropZone} ${dragActive ? styles.dropZoneActive : ''} ${file ? styles.dropZoneHasFile : ''}`}
            onDragEnter={handleDrag}
            onDragLeave={handleDrag}
            onDragOver={handleDrag}
            onDrop={handleDrop}
          >
            <input 
              type="file" 
              id="file-upload" 
              className={styles.fileInput} 
              onChange={handleFileChange}
              accept=".xlsx,.xls,.csv"
            />
            <label htmlFor="file-upload" className={styles.dropLabel}>
              <div className={styles.uploadIcon}>📥</div>
              {file ? (
                <div>
                  <p className={styles.fileName}>{file.name}</p>
                  <p className={styles.fileSize}>{(file.size / 1024).toFixed(1)} KB</p>
                </div>
              ) : (
                <div>
                  <p className={styles.dropText}>{t('import.dragText')} <span className={styles.browseText}>{t('import.browseText')}</span></p>
                  <p className={styles.supportedText}>{t('import.supportedText')}</p>
                </div>
              )}
            </label>
          </div>

          {isUploading && (
            <div className={styles.progressContainer}>
              <div className={styles.progressBarWrapper}>
                <div className={styles.progressBar} style={{ width: `${progress}%` }}></div>
              </div>
              <div className={styles.progressText}>
                <span>{t('import.uploading')} {progress}%</span>
                {statusMessage && <p className={styles.statusText}>{statusMessage}</p>}
              </div>
            </div>
          )}

          <div className={styles.actions}>
            <button 
              onClick={handleUpload} 
              disabled={!file || isUploading} 
              className={styles.btnPrimary}
              id="btn-submit-upload"
            >
              {t('import.process')}
            </button>
            {file && !isUploading && (
              <button 
                onClick={() => { setFile(null); setSuccessData(null); setValidationErrors([]); setGeneralError(null); }} 
                className={styles.btnSecondary}
                id="btn-clear-file"
              >
                {t('import.clear')}
              </button>
            )}
          </div>

          {successData && (
            <div className={styles.alertSuccess} id="upload-success-msg">
              <span className={styles.alertIcon}>✓</span>
              <div>
                <strong>{t('import.success')}</strong>
                <p>{t('import.successDesc').replace('{count}', String(successData.count))}</p>
                {successData.totalAmount !== undefined && <p>{t('import.consolidated')} ${successData.totalAmount.toLocaleString()}</p>}
              </div>
            </div>
          )}

          {generalError && (
            <div className={styles.alertError} id="upload-error-msg">
              <span className={styles.alertIcon}>⚠️</span>
              <div>
                <strong>{t('import.inconsistencyAlert')}</strong>
                <p>{generalError}</p>
              </div>
            </div>
          )}

          {validationErrors.length > 0 && (
            <div className={styles.inconsistencyContainer} id="inconsistency-panel">
              <h3 className={styles.inconsistencyTitle}>{t('import.inconsistencyTitle')}</h3>
              <div className={styles.tableWrapper}>
                <table className={styles.inconsistencyTable}>
                  <thead>
                    <tr>
                      <th>{t('import.thRow')}</th>
                      <th>{t('import.thColumn')}</th>
                      <th>{t('import.thValue')}</th>
                      <th>{t('import.thError')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {validationErrors.map((err, idx) => (
                      <tr key={idx} className={styles.inconsistencyRow}>
                        <td className={styles.cellRow}>{t('import.thRow')} {err.row}</td>
                        <td className={styles.cellCol}>{err.column}</td>
                        <td className={styles.cellVal}><code>{String(err.value || '')}</code></td>
                        <td className={styles.cellMsg}>{translate(err.code, err.metadata, err.value)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

        </div>
      </main>
    </div>
  );
}
