'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  uploadAndValidateImport,
  getTempImportRows,
  getTempImportErrorsReport,
  confirmImport,
  cancelImport
} from '@/lib/actions/import-export';
import { Button } from '@/components/ui/Button';
import { Card } from '@/components/ui/Card';
import Link from 'next/link';

export default function MemberImportPage() {
  const router = useRouter();

  // File states
  const [file, setFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Preview state
  const [preview, setPreview] = useState<any | null>(null);
  const [rows, setRows] = useState<any[]>([]);
  const [rowsPage, setRowsPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [isRowsLoading, setIsRowsLoading] = useState(false);

  // Overrides state (rowNumber -> 'ImportAsNew' | 'Skip')
  const [overrides, setOverrides] = useState<Record<number, 'ImportAsNew' | 'Skip'>>({});
  const [isConfirming, setIsConfirming] = useState(false);
  const [importResult, setImportResult] = useState<any | null>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setError(null);
    const selected = e.target.files?.[0];
    if (!selected) return;

    const ext = selected.name.split('.').pop()?.toLowerCase();
    if (ext !== 'csv' && ext !== 'xlsx') {
      setError('Unsupported file type: Only .csv and .xlsx files are allowed.');
      setFile(null);
      return;
    }

    if (selected.size > 5 * 1024 * 1024) {
      setError('File size limit exceeded: Maximum allowed size is 5MB.');
      setFile(null);
      return;
    }

    setFile(selected);
  };

  const handleUpload = async () => {
    if (!file) return;
    setIsUploading(true);
    setError(null);

    try {
      const reader = new FileReader();
      reader.onload = async (event) => {
        try {
          const base64 = (event.target?.result as string).split(',')[1];
          const result = await uploadAndValidateImport(base64, file.name, file.size);
          setPreview(result);
          await loadTempRows(result.batchId, 1);
        } catch (err: any) {
          setError(err.message || 'Validation failed. Please verify format.');
        } finally {
          setIsUploading(false);
        }
      };
      reader.onerror = () => {
        setError('Failed to read file.');
        setIsUploading(false);
      };
      reader.readAsDataURL(file);
    } catch (err: any) {
      setError(err.message || 'System upload error');
      setIsUploading(false);
    }
  };

  const loadTempRows = async (batchId: string, page: number) => {
    setIsRowsLoading(true);
    try {
      const res = await getTempImportRows(batchId, page, 20);
      setRows(res.items);
      setRowsPage(res.pagination.page);
      setTotalPages(res.pagination.pages);
    } catch (err: any) {
      console.error(err);
    } finally {
      setIsRowsLoading(false);
    }
  };

  const handleOverrideToggle = (rowNumber: number, currentStatus: string) => {
    setOverrides(prev => {
      const currentDecision = prev[rowNumber];
      let nextDecision: 'ImportAsNew' | 'Skip';

      if (currentDecision === 'ImportAsNew') {
        nextDecision = 'Skip';
      } else if (currentDecision === 'Skip') {
        nextDecision = 'ImportAsNew';
      } else {
        // Default was SKIP for warnings, so toggle makes it ImportAsNew
        nextDecision = 'ImportAsNew';
      }

      return { ...prev, [rowNumber]: nextDecision };
    });
  };

  const handleDownloadErrorsReport = async () => {
    if (!preview?.batchId) return;
    try {
      const csvContent = await getTempImportErrorsReport(preview.batchId);
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', `import_errors_${preview.batchId}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (err) {
      alert('Failed to generate error report file.');
    }
  };

  const handleConfirmImport = async () => {
    if (!preview?.batchId) return;
    setIsConfirming(true);
    setError(null);
    try {
      const result = await confirmImport(preview.batchId, overrides);
      setImportResult(result);
    } catch (err: any) {
      setError(err.message || 'Import failed during execution.');
    } finally {
      setIsConfirming(false);
    }
  };

  const handleCancelImport = async () => {
    if (!preview?.batchId) return;
    if (!confirm('Are you sure you want to discard this upload?')) return;
    try {
      await cancelImport(preview.batchId);
      setPreview(null);
      setRows([]);
      setFile(null);
      setOverrides({});
    } catch (err) {
      console.error(err);
    }
  };

  if (importResult) {
    return (
      <div className="max-w-xl mx-auto space-y-6 py-6">
        <Card className="p-8 text-center space-y-4 border-green-200 bg-green-50/10">
          <div className="h-14 w-14 bg-green-100 text-green-700 rounded-full flex items-center justify-center mx-auto text-3xl">
            ✓
          </div>
          <h2 className="text-2xl font-black text-gray-900">Import Job Complete</h2>
          <p className="text-sm text-gray-500 font-semibold">
            Members spreadsheet processed and synchronized with CRM.
          </p>

          <div className="grid grid-cols-3 gap-4 border-y border-gray-150 py-4 my-6">
            <div>
              <span className="text-[10px] font-bold text-gray-400 uppercase">Imported</span>
              <h3 className="text-2xl font-black text-green-700 mt-1">{importResult.importedCount}</h3>
            </div>
            <div>
              <span className="text-[10px] font-bold text-gray-400 uppercase">Skipped</span>
              <h3 className="text-2xl font-black text-yellow-700 mt-1">{importResult.skippedCount}</h3>
            </div>
            <div>
              <span className="text-[10px] font-bold text-gray-400 uppercase">Failed</span>
              <h3 className="text-2xl font-black text-red-700 mt-1">{importResult.failedCount}</h3>
            </div>
          </div>

          <div className="flex gap-4 justify-center">
            <Link href="/members">
              <Button className="bg-brand-primary text-white">Go Member Directory</Button>
            </Link>
            <Button variant="secondary" onClick={() => { setImportResult(null); setPreview(null); setFile(null); setOverrides({}); }}>
              Import Another File
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl md:text-3xl font-extrabold text-gray-900">Spreadsheet Member Import</h1>
        <p className="mt-1 text-sm text-gray-500">Upload existing Member spreadsheets (CSV/XLSX) to populate the CRM.</p>
      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-800 p-4 rounded-xl text-sm font-semibold flex items-center justify-between">
          <span>{error}</span>
          <button onClick={() => setError(null)} className="text-red-500 hover:text-red-700 font-bold ml-2">Dismiss</button>
        </div>
      )}

      {!preview ? (
        // File upload card
        <Card className="p-8 text-center space-y-6">
          <div className="border-2 border-dashed border-gray-250 rounded-xl p-8 bg-gray-50/50 hover:bg-gray-50 transition-all flex flex-col items-center">
            <span className="text-4xl text-gray-400 mb-2">📄</span>
            <span className="text-sm font-semibold text-gray-700">Select Spreadsheet file</span>
            <span className="text-xs text-gray-400 mt-1">Accepts CSV or XLSX files (max 5MB, 2000 rows)</span>
            <input
              type="file"
              accept=".csv, .xlsx"
              onChange={handleFileChange}
              className="mt-4 block w-full text-xs text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-semibold file:bg-orange-50 file:text-brand-primary hover:file:bg-orange-100 cursor-pointer"
            />
          </div>

          {file && (
            <div className="flex items-center justify-between bg-orange-50/30 p-3 rounded-lg border border-orange-100 text-xs font-semibold">
              <span className="text-gray-700">File: {file.name} ({(file.size / 1024).toFixed(1)} KB)</span>
              <Button onClick={handleUpload} isLoading={isUploading} className="bg-brand-primary text-white">
                Upload & Validate
              </Button>
            </div>
          )}
        </Card>
      ) : (
        // Preview, mapping validation board
        <div className="space-y-6">
          <Card className="p-6 space-y-4">
            <div className="flex justify-between items-center border-b border-gray-150 pb-3">
              <div>
                <h3 className="font-extrabold text-base text-gray-900">Validation Preview</h3>
                <span className="text-xs text-gray-400">File: {preview.filename} | Batch: {preview.batchId}</span>
              </div>
              <div className="flex gap-2">
                <Button variant="secondary" onClick={handleCancelImport} className="text-red-600 hover:bg-red-50 text-xs py-1 px-3">
                  Discard Upload
                </Button>
                {(preview.failedRows > 0 || preview.skippedRows > 0) && (
                  <Button onClick={handleDownloadErrorsReport} className="bg-yellow-600 hover:bg-yellow-700 text-white text-xs py-1 px-3">
                    📥 Download Error Report
                  </Button>
                )}
              </div>
            </div>

            {/* Validation Metrics */}
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 text-center">
              <div className="p-3 bg-gray-50 rounded-lg border border-gray-200">
                <span className="text-[10px] font-bold text-gray-400 uppercase">Total Rows</span>
                <h4 className="text-lg font-black text-gray-900 mt-1">{preview.totalRows}</h4>
              </div>
              <div className="p-3 bg-green-50/30 rounded-lg border border-green-200">
                <span className="text-[10px] font-bold text-gray-400 uppercase">Ready</span>
                <h4 className="text-lg font-black text-green-700 mt-1">{preview.successRows}</h4>
              </div>
              <div className="p-3 bg-yellow-50/30 rounded-lg border border-yellow-200">
                <span className="text-[10px] font-bold text-gray-400 uppercase">Warnings / Dups</span>
                <h4 className="text-lg font-black text-yellow-700 mt-1">{preview.skippedRows}</h4>
              </div>
              <div className="p-3 bg-red-50/30 rounded-lg border border-red-200">
                <span className="text-[10px] font-bold text-gray-400 uppercase">Errors</span>
                <h4 className="text-lg font-black text-red-700 mt-1">{preview.failedRows}</h4>
              </div>
            </div>

            {/* Headers Mapping Visualizer Info */}
            <div className="bg-blue-50/20 border border-blue-200 p-4 rounded-xl text-xs space-y-2">
              <h4 className="font-bold text-blue-800">Automatic Column mapping Suggestions</h4>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-gray-600 mt-2">
                <div>Name ➔ <span className="font-bold text-gray-900">"{preview.columnMap.name || 'None'}"</span></div>
                <div>Mobile ➔ <span className="font-bold text-gray-900">"{preview.columnMap.mobile || 'None'}"</span></div>
                <div>City ➔ <span className="font-bold text-gray-900">"{preview.columnMap.city || 'None'}"</span></div>
                <div>Area ➔ <span className="font-bold text-gray-900">"{preview.columnMap.area || 'None'}"</span></div>
              </div>
            </div>
          </Card>

          {/* Validation Rows Detail Table */}
          <Card className="p-6">
            <h3 className="font-bold text-base text-gray-900 mb-4">Spreadsheet Validation details</h3>
            <div className="overflow-x-auto border border-gray-150 rounded-lg">
              <table className="min-w-full divide-y divide-gray-150 text-xs">
                <thead className="bg-gray-50 text-gray-500 font-semibold">
                  <tr>
                    <th className="px-4 py-3 text-left">Row</th>
                    <th className="px-4 py-3 text-left">Name</th>
                    <th className="px-4 py-3 text-left">Mobile</th>
                    <th className="px-4 py-3 text-left">City / Area</th>
                    <th className="px-4 py-3 text-left">Status</th>
                    <th className="px-4 py-3 text-left">Decision / Override</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-150 bg-white">
                  {isRowsLoading ? (
                    <tr>
                      <td colSpan={6} className="text-center py-10 text-gray-400">Loading parsed rows details...</td>
                    </tr>
                  ) : rows.length === 0 ? (
                    <tr>
                      <td colSpan={6} className="text-center py-10 text-gray-400">No rows details available.</td>
                    </tr>
                  ) : (
                    rows.map(row => {
                      const isWarning = row.status === 'Warning';
                      const isError = row.status === 'Error';
                      const overrideDecision = overrides[row.rowNumber];
                      
                      // Resolve row defaults
                      let defaultDecision = 'Import';
                      if (isError) defaultDecision = 'Skip (Error)';
                      else if (isWarning) defaultDecision = 'Skip (Duplicate)';

                      const activeDecision = overrideDecision || defaultDecision;

                      return (
                        <tr key={row._id}>
                          <td className="px-4 py-3 font-semibold text-gray-500">{row.rowNumber}</td>
                          <td className="px-4 py-3 font-bold text-gray-900">{row.name}</td>
                          <td className="px-4 py-3">{row.mobile || '-'}</td>
                          <td className="px-4 py-3 text-gray-600">{row.rawCity} / {row.rawArea}</td>
                          <td className="px-4 py-3">
                            <span className={`inline-block px-2 py-0.5 rounded-full text-[10px] font-bold ${
                              isError ? 'bg-red-100 text-red-700' : isWarning ? 'bg-yellow-100 text-yellow-800' : 'bg-green-100 text-green-700'
                            }`}>
                              {row.status}
                            </span>
                            {row.reason && (
                              <p className="text-[10px] text-gray-400 font-semibold mt-0.5">{row.reason}</p>
                            )}
                          </td>
                          <td className="px-4 py-3">
                            {isError ? (
                              <span className="text-red-500 font-bold">Block (Fix Excel)</span>
                            ) : isWarning ? (
                              <button
                                onClick={() => handleOverrideToggle(row.rowNumber, row.status)}
                                className={`px-3 py-1.5 rounded-lg border font-bold text-[10px] transition-all touch-target ${
                                  activeDecision === 'ImportAsNew'
                                    ? 'bg-orange-50 border-brand-primary text-brand-primary'
                                    : 'bg-gray-50 border-gray-200 text-gray-500 hover:border-brand-primary hover:text-brand-primary'
                                }`}
                              >
                                {activeDecision === 'ImportAsNew' ? '✓ Import as New' : 'Skip (Duplicate)'}
                              </button>
                            ) : (
                              <span className="text-green-700 font-semibold">Import</span>
                            )}
                          </td>
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </div>

            {/* Table Pagination Controls */}
            {totalPages > 1 && (
              <div className="flex justify-between items-center mt-4 text-xs font-semibold">
                <Button
                  variant="secondary"
                  disabled={rowsPage === 1 || isRowsLoading}
                  onClick={() => loadTempRows(preview.batchId, rowsPage - 1)}
                  className="py-1 px-3"
                >
                  ◀ Previous
                </Button>
                <span className="text-gray-500">Page {rowsPage} of {totalPages}</span>
                <Button
                  variant="secondary"
                  disabled={rowsPage === totalPages || isRowsLoading}
                  onClick={() => loadTempRows(preview.batchId, rowsPage + 1)}
                  className="py-1 px-3"
                >
                  Next ▶
                </Button>
              </div>
            )}
          </Card>

          {/* Confirm Import Trigger Card */}
          <Card className="p-6 flex justify-between items-center bg-orange-50/10 border-orange-200">
            <p className="text-xs text-gray-500 font-semibold leading-relaxed">
              Verify headers suggestions, validation error logs, and duplicate warnings decisions overrides before confirmation.
            </p>
            <Button
              onClick={handleConfirmImport}
              isLoading={isConfirming}
              disabled={preview.successRows === 0 && Object.values(overrides).filter(d => d === 'ImportAsNew').length === 0}
              className="bg-brand-primary hover:bg-brand-secondary text-white font-bold"
            >
              Confirm Import Checklist
            </Button>
          </Card>
        </div>
      )}
    </div>
  );
}
