import React, { useState } from 'react';
import api from '../../store/api';
import { exportToCsv } from '../../utils/csv';
import { 
  Upload, 
  FileSpreadsheet, 
  CheckCircle2, 
  AlertTriangle, 
  XCircle, 
  ArrowRight, 
  ArrowLeft, 
  Download, 
  RefreshCw,
  Database,
  Users,
  Building2,
  UserCheck
} from 'lucide-react';
import { ProgressBar } from '../../components/ui/ProgressBar';

interface PreviewRow {
  row_number: number;
  data: Record<string, string>;
  parsed_fields: {
    first_name: string;
    last_name: string;
    email: string;
    class_name: string;
  };
  is_valid: boolean;
  errors: string[];
  warnings: string[];
}

interface PreviewResponse {
  total_rows: number;
  valid_rows_count: number;
  error_rows_count: number;
  headers: string[];
  auto_mapping: Record<string, string>;
  sample_rows: PreviewRow[];
}

interface CommitResponse {
  inserted_students: number;
  created_classes: number;
  linked_parents: number;
  errors: Array<{ row: number; error: string }>;
}

export default function LegacyImport() {
  const [step, setStep] = useState<1 | 2 | 3 | 4>(1);
  const [csvText, setCsvText] = useState<string>('');
  const [fileName, setFileName] = useState<string>('');
  const [previewData, setPreviewData] = useState<PreviewResponse | null>(null);
  const [columnMapping, setColumnMapping] = useState<Record<string, string>>({});
  const [autoCreateClasses, setAutoCreateClasses] = useState<boolean>(true);
  const [defaultPassword, setDefaultPassword] = useState<string>('student123');
  const [loading, setLoading] = useState<boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string>('');
  const [commitResult, setCommitResult] = useState<CommitResponse | null>(null);

  const targetFields = [
    { key: 'first_name', label: 'First Name *' },
    { key: 'last_name', label: 'Last Name *' },
    { key: 'email', label: 'Email' },
    { key: 'phone', label: 'Phone' },
    { key: 'gender', label: 'Gender' },
    { key: 'class_name', label: 'Class / Form' },
    { key: 'roll_number', label: 'Roll Number / Reg No' },
    { key: 'parent_name', label: 'Parent / Guardian Name' },
    { key: 'parent_phone', label: 'Parent Contact Phone' },
    { key: 'parent_email', label: 'Parent Contact Email' }
  ];

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setFileName(file.name);
    const reader = new FileReader();
    reader.onload = (event) => {
      const content = event.target?.result as string;
      setCsvText(content);
      setErrorMessage('');
    };
    reader.readAsText(file);
  };

  const downloadSampleCsv = () => {
    const sampleRows = [
      {
        'First Name': 'Tafadzwa',
        'Last Name': 'Moyo',
        'Email': 'tafadzwa.moyo@school.co.zw',
        'Phone': '0771234567',
        'Gender': 'Male',
        'Class': 'Form 1A',
        'Roll': '101',
        'Parent Name': 'Grace Moyo',
        'Parent Phone': '0779998888',
        'Parent Email': 'grace.moyo@gmail.com'
      },
      {
        'First Name': 'Chipo',
        'Last Name': 'Ncube',
        'Email': 'chipo.ncube@school.co.zw',
        'Phone': '0777654321',
        'Gender': 'Female',
        'Class': 'Form 1A',
        'Roll': '102',
        'Parent Name': 'Kudzai Ncube',
        'Parent Phone': '0771112222',
        'Parent Email': 'kudzai.ncube@gmail.com'
      }
    ];

    exportToCsv('legacy_student_import_sample.csv', sampleRows, [
      { key: 'First Name', label: 'First Name' },
      { key: 'Last Name', label: 'Last Name' },
      { key: 'Email', label: 'Email' },
      { key: 'Phone', label: 'Phone' },
      { key: 'Gender', label: 'Gender' },
      { key: 'Class', label: 'Class' },
      { key: 'Roll', label: 'Roll' },
      { key: 'Parent Name', label: 'Parent Name' },
      { key: 'Parent Phone', label: 'Parent Phone' },
      { key: 'Parent Email', label: 'Parent Email' }
    ]);
  };

  const handlePreview = async () => {
    if (!csvText.trim()) {
      setErrorMessage('Please select or paste a CSV file to continue.');
      return;
    }

    setLoading(true);
    setUploadProgress(15);
    setProgressLabel('Uploading CSV and parsing headers...');
    setErrorMessage('');

    const timer = setInterval(() => {
      setUploadProgress((p) => (p < 85 ? p + 15 : p));
    }, 150);

    try {
      const res = await api.post<PreviewResponse>('/students/import/preview', { csvContent: csvText });
      setUploadProgress(100);
      setPreviewData(res.data);
      setColumnMapping(res.data.auto_mapping || {});
      setStep(2);
    } catch (err: any) {
      setErrorMessage(err.response?.data?.error || 'Failed to process CSV preview');
    } finally {
      clearInterval(timer);
      setLoading(false);
    }
  };

  const handleCommit = async () => {
    setLoading(true);
    setUploadProgress(20);
    setProgressLabel('Committing legacy student records, classes, and parent accounts...');
    setErrorMessage('');

    const timer = setInterval(() => {
      setUploadProgress((p) => (p < 90 ? p + 10 : p));
    }, 250);

    try {
      const res = await api.post<CommitResponse>('/students/import/commit', {
        csvContent: csvText,
        mapping: columnMapping,
        options: {
          autoCreateClasses,
          defaultPassword
        }
      });
      setUploadProgress(100);
      setCommitResult(res.data);
      setStep(4);
    } catch (err: any) {
      setErrorMessage(err.response?.data?.error || 'Failed to complete legacy data import');
    } finally {
      clearInterval(timer);
      setLoading(false);
    }
  };

  const downloadErrorCsv = () => {
    if (!commitResult?.errors || commitResult.errors.length === 0) return;
    exportToCsv('import_errors.csv', commitResult.errors, [
      { key: 'row', label: 'CSV Row Number' },
      { key: 'error', label: 'Error Diagnostic' }
    ]);
  };

  return (
    <div className="p-6 max-w-7xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-gradient-to-r from-blue-900 via-indigo-900 to-slate-900 text-white p-6 rounded-2xl shadow-xl">
        <div>
          <div className="flex items-center gap-3">
            <div className="p-3 bg-blue-500/20 rounded-xl border border-blue-400/30 backdrop-blur-md">
              <Database className="w-8 h-8 text-blue-300" />
            </div>
            <div>
              <h1 className="text-2xl font-bold tracking-tight">Legacy CSV Data Importer</h1>
              <p className="text-blue-200 text-sm">
                Import legacy student registers, class sections, and parent contact records (FR-SMS3)
              </p>
            </div>
          </div>
        </div>
        <button
          onClick={downloadSampleCsv}
          className="flex items-center gap-2 px-4 py-2 bg-white/10 hover:bg-white/20 border border-white/20 rounded-xl text-sm font-medium transition backdrop-blur-md self-start md:self-auto"
        >
          <Download className="w-4 h-4" />
          Download CSV Template
        </button>
      </div>

      {/* Step Progress Indicator */}
      <div className="grid grid-cols-4 gap-2 bg-white dark:bg-slate-800 p-2 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm">
        {[
          { num: 1, title: '1. Upload File' },
          { num: 2, title: '2. Map Columns' },
          { num: 3, title: '3. Validate' },
          { num: 4, title: '4. Complete' }
        ].map((s) => (
          <div
            key={s.num}
            className={`py-3 px-4 rounded-xl font-medium text-sm text-center transition flex items-center justify-center gap-2 ${
              step === s.num
                ? 'bg-blue-600 text-white shadow-md'
                : step > s.num
                ? 'bg-emerald-50 dark:bg-emerald-950/40 text-emerald-700 dark:text-emerald-300 border border-emerald-200/50'
                : 'text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700/50'
            }`}
          >
            {step > s.num ? <CheckCircle2 className="w-4 h-4 text-emerald-600" /> : null}
            <span>{s.title}</span>
          </div>
        ))}
      </div>

      {/* Loading Progress Bar */}
      {loading && (
        <ProgressBar
          progress={uploadProgress}
          label={progressLabel || 'Processing bulk import data...'}
          sublabel="Parsing columns, validating relationships, and committing database entries."
          color="indigo"
        />
      )}

      {/* Error Message */}
      {errorMessage && (
        <div className="p-4 bg-rose-50 border border-rose-200 text-rose-800 rounded-xl flex items-center gap-3">
          <AlertTriangle className="w-5 h-5 shrink-0" />
          <p className="text-sm font-medium">{errorMessage}</p>
        </div>
      )}

      {/* STEP 1: Upload */}
      {step === 1 && (
        <div className="bg-white dark:bg-slate-800 p-8 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm space-y-6">
          <div className="text-center max-w-xl mx-auto space-y-2">
            <h2 className="text-lg font-semibold text-slate-900 dark:text-white">Select Legacy Register CSV File</h2>
            <p className="text-sm text-slate-500 dark:text-slate-400">
              Upload any standard CSV file containing student names, forms/classes, and parent details.
            </p>
          </div>

          <div className="border-2 border-dashed border-slate-300 dark:border-slate-600 hover:border-blue-500 rounded-2xl p-10 text-center bg-slate-50 dark:bg-slate-900/40 transition cursor-pointer relative">
            <input
              type="file"
              accept=".csv,text/csv"
              onChange={handleFileUpload}
              className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
            />
            <div className="flex flex-col items-center gap-3">
              <div className="p-4 bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 rounded-full">
                <FileSpreadsheet className="w-10 h-10" />
              </div>
              <div>
                <p className="font-semibold text-slate-900 dark:text-white">
                  {fileName ? fileName : 'Click to select CSV file or drag and drop here'}
                </p>
                <p className="text-xs text-slate-500 mt-1">UTF-8 encoded CSV files up to 50MB</p>
              </div>
            </div>
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium text-slate-700 dark:text-slate-300">
              Or paste raw CSV text content:
            </label>
            <textarea
              rows={6}
              value={csvText}
              onChange={(e) => setCsvText(e.target.value)}
              placeholder="First Name,Last Name,Email,Class,Parent Name,Parent Phone..."
              className="w-full p-4 border border-slate-300 dark:border-slate-700 rounded-xl bg-white dark:bg-slate-900 text-sm font-mono focus:ring-2 focus:ring-blue-500 outline-none"
            />
          </div>

          <div className="flex justify-end">
            <button
              onClick={handlePreview}
              disabled={loading || !csvText.trim()}
              className="flex items-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white font-medium rounded-xl shadow-md transition"
            >
              {loading ? (
                <>
                  <RefreshCw className="w-5 h-5 animate-spin" />
                  Analyzing CSV...
                </>
              ) : (
                <>
                  Next: Map Columns
                  <ArrowRight className="w-5 h-5" />
                </>
              )}
            </button>
          </div>
        </div>
      )}

      {/* STEP 2: Map Columns */}
      {step === 2 && previewData && (
        <div className="bg-white dark:bg-slate-800 p-8 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm space-y-6">
          <div className="flex items-center justify-between pb-4 border-b border-slate-200 dark:border-slate-700">
            <div>
              <h2 className="text-lg font-semibold text-slate-900 dark:text-white">Map CSV Headers to System Fields</h2>
              <p className="text-sm text-slate-500 dark:text-slate-400">
                Match each system target field to the appropriate column header detected in your CSV file.
              </p>
            </div>
            <span className="px-3 py-1 bg-blue-100 dark:bg-blue-900/40 text-blue-800 dark:text-blue-300 rounded-full text-xs font-semibold">
              {previewData.headers.length} CSV Columns Detected
            </span>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {targetFields.map((field) => (
              <div
                key={field.key}
                className="p-4 bg-slate-50 dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-slate-700 flex flex-col gap-2"
              >
                <label className="text-xs font-semibold uppercase tracking-wider text-slate-600 dark:text-slate-400">
                  {field.label}
                </label>
                <select
                  value={columnMapping[field.key] || ''}
                  onChange={(e) =>
                    setColumnMapping({ ...columnMapping, [field.key]: e.target.value })
                  }
                  className="p-2.5 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-700 rounded-lg text-sm font-medium focus:ring-2 focus:ring-blue-500 outline-none"
                >
                  <option value="">-- Do Not Import / Skip --</option>
                  {previewData.headers.map((h) => (
                    <option key={h} value={h}>
                      {h}
                    </option>
                  ))}
                </select>
              </div>
            ))}
          </div>

          <div className="flex justify-between pt-4 border-t border-slate-200 dark:border-slate-700">
            <button
              onClick={() => setStep(1)}
              className="flex items-center gap-2 px-5 py-2.5 border border-slate-300 dark:border-slate-600 rounded-xl text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 font-medium transition"
            >
              <ArrowLeft className="w-4 h-4" />
              Back
            </button>
            <button
              onClick={() => setStep(3)}
              className="flex items-center gap-2 px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-xl shadow-md transition"
            >
              Next: Review & Dry-Run
              <ArrowRight className="w-5 h-5" />
            </button>
          </div>
        </div>
      )}

      {/* STEP 3: Preview & Dry-Run */}
      {step === 3 && previewData && (
        <div className="bg-white dark:bg-slate-800 p-8 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm space-y-6">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
              <h2 className="text-lg font-semibold text-slate-900 dark:text-white">Validation Summary & Options</h2>
              <p className="text-sm text-slate-500 dark:text-slate-400">
                Review data row sanity diagnostics before executing bulk database insertion.
              </p>
            </div>
            <div className="flex items-center gap-3">
              <div className="px-4 py-2 bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300 rounded-xl border border-emerald-200/50 text-sm font-semibold flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4" />
                {previewData.valid_rows_count} Valid Rows
              </div>
              {previewData.error_rows_count > 0 && (
                <div className="px-4 py-2 bg-rose-50 text-rose-700 dark:bg-rose-950/40 dark:text-rose-300 rounded-xl border border-rose-200/50 text-sm font-semibold flex items-center gap-2">
                  <XCircle className="w-4 h-4" />
                  {previewData.error_rows_count} Error Rows
                </div>
              )}
            </div>
          </div>

          {/* Import Settings Card */}
          <div className="p-4 bg-slate-50 dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-slate-700 grid grid-cols-1 md:grid-cols-2 gap-4">
            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                checked={autoCreateClasses}
                onChange={(e) => setAutoCreateClasses(e.target.checked)}
                className="w-5 h-5 text-blue-600 rounded border-slate-300 focus:ring-blue-500"
              />
              <div>
                <span className="text-sm font-semibold text-slate-900 dark:text-white">
                  Auto-create missing class sections
                </span>
                <p className="text-xs text-slate-500">Automatically add class sections if they do not exist in system</p>
              </div>
            </label>

            <div>
              <label className="text-xs font-semibold uppercase tracking-wider text-slate-600 dark:text-slate-400">
                Default Student Initial Password
              </label>
              <input
                type="text"
                value={defaultPassword}
                onChange={(e) => setDefaultPassword(e.target.value)}
                className="w-full mt-1 p-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-700 rounded-lg text-sm font-mono outline-none"
              />
            </div>
          </div>

          {/* Preview Rows Table */}
          <div className="border border-slate-200 dark:border-slate-700 rounded-xl overflow-hidden">
            <div className="max-h-96 overflow-y-auto">
              <table className="w-full text-left text-sm">
                <thead className="bg-slate-100 dark:bg-slate-900/80 sticky top-0 font-semibold text-slate-700 dark:text-slate-300 border-b border-slate-200 dark:border-slate-700">
                  <tr>
                    <th className="p-3 w-16 text-center">Row</th>
                    <th className="p-3">Parsed Student Name</th>
                    <th className="p-3">Email</th>
                    <th className="p-3">Class</th>
                    <th className="p-3">Validation Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-200 dark:divide-slate-700">
                  {previewData.sample_rows.map((r) => (
                    <tr key={r.row_number} className="hover:bg-slate-50 dark:hover:bg-slate-700/30">
                      <td className="p-3 text-center text-xs font-mono text-slate-500">{r.row_number}</td>
                      <td className="p-3 font-medium text-slate-900 dark:text-white">
                        {r.parsed_fields.first_name} {r.parsed_fields.last_name}
                      </td>
                      <td className="p-3 text-slate-600 dark:text-slate-400">{r.parsed_fields.email || '--'}</td>
                      <td className="p-3 text-slate-600 dark:text-slate-400">{r.parsed_fields.class_name || '--'}</td>
                      <td className="p-3">
                        {r.is_valid ? (
                          <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-emerald-100 text-emerald-800 dark:bg-emerald-950/60 dark:text-emerald-300 rounded-full text-xs font-medium">
                            <CheckCircle2 className="w-3.5 h-3.5" /> Valid
                          </span>
                        ) : (
                          <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-rose-100 text-rose-800 dark:bg-rose-950/60 dark:text-rose-300 rounded-full text-xs font-medium">
                            <XCircle className="w-3.5 h-3.5" /> {r.errors.join(', ')}
                          </span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          <div className="flex justify-between pt-4 border-t border-slate-200 dark:border-slate-700">
            <button
              onClick={() => setStep(2)}
              className="flex items-center gap-2 px-5 py-2.5 border border-slate-300 dark:border-slate-600 rounded-xl text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 font-medium transition"
            >
              <ArrowLeft className="w-4 h-4" />
              Back
            </button>
            <button
              onClick={handleCommit}
              disabled={loading}
              className="flex items-center gap-2 px-6 py-2.5 bg-emerald-600 hover:bg-emerald-700 disabled:opacity-50 text-white font-medium rounded-xl shadow-lg transition"
            >
              {loading ? (
                <>
                  <RefreshCw className="w-5 h-5 animate-spin" />
                  Importing to Database...
                </>
              ) : (
                <>
                  <Upload className="w-5 h-5" />
                  Execute Transactional Import
                </>
              )}
            </button>
          </div>
        </div>
      )}

      {/* STEP 4: Summary & Complete */}
      {step === 4 && commitResult && (
        <div className="bg-white dark:bg-slate-800 p-8 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm space-y-6 text-center max-w-2xl mx-auto">
          <div className="w-16 h-16 bg-emerald-100 dark:bg-emerald-950 text-emerald-600 dark:text-emerald-300 rounded-full flex items-center justify-center mx-auto shadow-inner">
            <UserCheck className="w-10 h-10" />
          </div>

          <div className="space-y-2">
            <h2 className="text-2xl font-bold text-slate-900 dark:text-white">Import Transaction Completed!</h2>
            <p className="text-sm text-slate-500 dark:text-slate-400">
              Legacy student register, class enrollments, and parent links have been safely committed.
            </p>
          </div>

          {/* Metric Cards */}
          <div className="grid grid-cols-3 gap-4 pt-2">
            <div className="p-4 bg-slate-50 dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-slate-700">
              <Users className="w-6 h-6 text-blue-600 mx-auto mb-1" />
              <p className="text-2xl font-bold text-slate-900 dark:text-white">{commitResult.inserted_students}</p>
              <p className="text-xs text-slate-500 font-medium">Students Added</p>
            </div>
            <div className="p-4 bg-slate-50 dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-slate-700">
              <Building2 className="w-6 h-6 text-indigo-600 mx-auto mb-1" />
              <p className="text-2xl font-bold text-slate-900 dark:text-white">{commitResult.created_classes}</p>
              <p className="text-xs text-slate-500 font-medium">Classes Created</p>
            </div>
            <div className="p-4 bg-slate-50 dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-slate-700">
              <UserCheck className="w-6 h-6 text-emerald-600 mx-auto mb-1" />
              <p className="text-2xl font-bold text-slate-900 dark:text-white">{commitResult.linked_parents}</p>
              <p className="text-xs text-slate-500 font-medium">Parents Linked</p>
            </div>
          </div>

          {commitResult.errors && commitResult.errors.length > 0 && (
            <div className="p-4 bg-amber-50 dark:bg-amber-950/40 border border-amber-200/60 rounded-xl text-left space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm font-semibold text-amber-900 dark:text-amber-300">
                  {commitResult.errors.length} Row Exceptions Encountered
                </span>
                <button
                  onClick={downloadErrorCsv}
                  className="text-xs font-semibold text-amber-700 underline hover:text-amber-800"
                >
                  Download Error Log CSV
                </button>
              </div>
              <ul className="text-xs text-amber-800 dark:text-amber-400 space-y-1 max-h-32 overflow-y-auto">
                {commitResult.errors.map((e, idx) => (
                  <li key={idx}>
                    Row {e.row}: {e.error}
                  </li>
                ))}
              </ul>
            </div>
          )}

          <div className="pt-4 flex justify-center gap-4">
            <button
              onClick={() => {
                setStep(1);
                setCsvText('');
                setFileName('');
                setPreviewData(null);
                setCommitResult(null);
              }}
              className="px-6 py-2.5 bg-slate-900 hover:bg-slate-800 text-white font-medium rounded-xl shadow-md transition"
            >
              Import Another Register
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
