import React, { useState } from 'react';
import {
  X,
  Download,
  FileSpreadsheet,
  Check,
  Filter,
  Calendar,
  Table,
  FileText,
  ShieldCheck,
  Copy,
  Layers,
  CheckCircle2,
  Building,
  Users,
  Award,
} from 'lucide-react';
import { StudentApplication, AttendanceRecord, FeePayment, Course, User, GradeItem } from '../types';
import {
  generateStudentRegistrationsCsv,
  generateAttendanceRecordsCsv,
  generateConsolidatedAuditReportCsv,
  triggerCsvDownload,
} from '../utils/exportCsv';

interface BulkExportModalProps {
  isOpen: boolean;
  onClose: () => void;
  applications: StudentApplication[];
  attendance: AttendanceRecord[];
  fees: FeePayment[];
  courses: Course[];
  allUsers: User[];
  grades: GradeItem[];
}

export const BulkExportModal: React.FC<BulkExportModalProps> = ({
  isOpen,
  onClose,
  applications,
  attendance,
  fees,
  courses,
  allUsers,
  grades,
}) => {
  if (!isOpen) return null;

  // Selected export category
  const [exportType, setExportType] = useState<'registrations' | 'attendance' | 'consolidated'>('registrations');

  // Filters for registrations
  const [regCourseFilter, setRegCourseFilter] = useState('all');
  const [regStatusFilter, setRegStatusFilter] = useState('all');
  const [regStudyModeFilter, setRegStudyModeFilter] = useState('all');

  // Filters for attendance
  const [attCourseFilter, setAttCourseFilter] = useState('all');
  const [attStatusFilter, setAttStatusFilter] = useState('all');
  const [attStudentSearch, setAttStudentSearch] = useState('');

  // Date filters
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  // Status feedback
  const [downloadSuccess, setDownloadSuccess] = useState(false);
  const [copiedSuccess, setCopiedSuccess] = useState(false);
  const [showPreviewTable, setShowPreviewTable] = useState(true);

  // Compute active dataset results
  let exportResult = {
    csvString: '',
    count: 0,
    filename: '',
  };

  if (exportType === 'registrations') {
    exportResult = generateStudentRegistrationsCsv(applications, courses, fees, {
      courseCode: regCourseFilter,
      status: regStatusFilter,
      studyMode: regStudyModeFilter,
      startDate: startDate || undefined,
      endDate: endDate || undefined,
    });
  } else if (exportType === 'attendance') {
    exportResult = generateAttendanceRecordsCsv(attendance, applications, allUsers, courses, {
      courseCode: attCourseFilter,
      status: attStatusFilter,
      studentId: attStudentSearch || undefined,
      startDate: startDate || undefined,
      endDate: endDate || undefined,
    });
  } else {
    exportResult = generateConsolidatedAuditReportCsv(applications, attendance, fees, courses, grades);
  }

  // Parse lines for the preview table
  const lines = exportResult.csvString
    .replace(/^\uFEFF/, '')
    .split('\r\n')
    .filter(l => l.trim().length > 0);

  const parseCsvLine = (line: string): string[] => {
    const result: string[] = [];
    let current = '';
    let inQuotes = false;
    for (let i = 0; i < line.length; i++) {
      const char = line[i];
      if (char === '"' && line[i + 1] === '"') {
        current += '"';
        i++;
      } else if (char === '"') {
        inQuotes = !inQuotes;
      } else if (char === ',' && !inQuotes) {
        result.push(current);
        current = '';
      } else {
        current += char;
      }
    }
    result.push(current);
    return result;
  };

  const previewHeaders = lines.length > 0 ? parseCsvLine(lines[0]) : [];
  const previewRows = lines.slice(1, 6).map(parseCsvLine);

  const handleDownload = () => {
    triggerCsvDownload(exportResult.filename, exportResult.csvString);
    setDownloadSuccess(true);
    setTimeout(() => setDownloadSuccess(false), 3500);
  };

  const handleCopyClipboard = async () => {
    try {
      await navigator.clipboard.writeText(exportResult.csvString.replace(/^\uFEFF/, ''));
      setCopiedSuccess(true);
      setTimeout(() => setCopiedSuccess(false), 3000);
    } catch (err) {
      console.error('Failed to copy CSV:', err);
    }
  };

  const resetFilters = () => {
    setRegCourseFilter('all');
    setRegStatusFilter('all');
    setRegStudyModeFilter('all');
    setAttCourseFilter('all');
    setAttStatusFilter('all');
    setAttStudentSearch('');
    setStartDate('');
    setEndDate('');
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/75 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-2xl max-w-4xl w-full overflow-hidden border border-slate-200 animate-in fade-in zoom-in-95 my-4 flex flex-col max-h-[92vh]">
        
        {/* Header */}
        <div className="bg-slate-900 text-white px-6 py-4 flex items-center justify-between border-b border-slate-800 shrink-0">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-emerald-600 flex items-center justify-center text-white shadow-md">
              <FileSpreadsheet className="w-5 h-5" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-base font-bold text-white tracking-tight">
                  Academic Registry Bulk Data Export
                </h2>
                <span className="bg-emerald-500/20 text-emerald-300 font-mono text-[10px] font-bold px-2 py-0.5 rounded border border-emerald-500/40">
                  CSV • RFC 4180
                </span>
              </div>
              <p className="text-xs text-slate-300">
                Official institutional exports for local filing, regulatory audit & offline archive compliance.
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-1.5 text-slate-400 hover:text-white rounded-lg transition hover:bg-slate-800"
            aria-label="Close modal"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Modal Body */}
        <div className="p-5 sm:p-6 overflow-y-auto space-y-5 text-xs">
          
          {/* Export Type Selector Tabs */}
          <div>
            <label className="block font-bold text-slate-800 uppercase tracking-wider text-[11px] mb-2">
              Select Dataset Category:
            </label>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              
              {/* Option 1: Registrations */}
              <button
                type="button"
                onClick={() => setExportType('registrations')}
                className={`p-3.5 rounded-xl border text-left transition flex flex-col justify-between ${
                  exportType === 'registrations'
                    ? 'border-emerald-600 bg-emerald-50/70 shadow-xs ring-2 ring-emerald-500/20'
                    : 'border-slate-200 bg-white hover:bg-slate-50'
                }`}
              >
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-2">
                    <FileText className={`w-4 h-4 ${exportType === 'registrations' ? 'text-emerald-700' : 'text-slate-500'}`} />
                    <span className="font-bold text-slate-900 text-xs">Admissions & Registrations</span>
                  </div>
                  {exportType === 'registrations' && (
                    <span className="w-2 h-2 rounded-full bg-emerald-600"></span>
                  )}
                </div>
                <p className="text-[11px] text-slate-600 mt-2 leading-relaxed">
                  Student profiles, MSCE points, guardian contacts, bank slips, and fee accounts.
                </p>
                <div className="mt-2 text-[10px] font-mono text-emerald-800 font-semibold">
                  {applications.length} Total Applicants
                </div>
              </button>

              {/* Option 2: Attendance */}
              <button
                type="button"
                onClick={() => setExportType('attendance')}
                className={`p-3.5 rounded-xl border text-left transition flex flex-col justify-between ${
                  exportType === 'attendance'
                    ? 'border-blue-600 bg-blue-50/70 shadow-xs ring-2 ring-blue-500/20'
                    : 'border-slate-200 bg-white hover:bg-slate-50'
                }`}
              >
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-2">
                    <Users className={`w-4 h-4 ${exportType === 'attendance' ? 'text-blue-700' : 'text-slate-500'}`} />
                    <span className="font-bold text-slate-900 text-xs">Attendance & Roll-Call Logs</span>
                  </div>
                  {exportType === 'attendance' && (
                    <span className="w-2 h-2 rounded-full bg-blue-600"></span>
                  )}
                </div>
                <p className="text-[11px] text-slate-600 mt-2 leading-relaxed">
                  Daily register marks, session names, lecturer sign-offs, tardiness notes & parent alerts.
                </p>
                <div className="mt-2 text-[10px] font-mono text-blue-800 font-semibold">
                  {attendance.length} Attendance Logs
                </div>
              </button>

              {/* Option 3: Consolidated Audit */}
              <button
                type="button"
                onClick={() => setExportType('consolidated')}
                className={`p-3.5 rounded-xl border text-left transition flex flex-col justify-between ${
                  exportType === 'consolidated'
                    ? 'border-purple-600 bg-purple-50/70 shadow-xs ring-2 ring-purple-500/20'
                    : 'border-slate-200 bg-white hover:bg-slate-50'
                }`}
              >
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-2">
                    <Award className={`w-4 h-4 ${exportType === 'consolidated' ? 'text-purple-700' : 'text-slate-500'}`} />
                    <span className="font-bold text-slate-900 text-xs">Consolidated Audit Master</span>
                  </div>
                  {exportType === 'consolidated' && (
                    <span className="w-2 h-2 rounded-full bg-purple-600"></span>
                  )}
                </div>
                <p className="text-[11px] text-slate-600 mt-2 leading-relaxed">
                  Compliance master sheet: attendance %, financial standing, and exam eligibility.
                </p>
                <div className="mt-2 text-[10px] font-mono text-purple-800 font-semibold">
                  Full Institutional Audit
                </div>
              </button>
            </div>
          </div>

          {/* Filtering Criteria Section */}
          <div className="bg-slate-50 p-4 rounded-xl border border-slate-200 space-y-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2 text-slate-800 font-bold text-xs">
                <Filter className="w-3.5 h-3.5 text-slate-600" />
                <span>Export Filter Parameters:</span>
              </div>
              <button
                onClick={resetFilters}
                className="text-[11px] text-emerald-700 hover:text-emerald-800 font-semibold hover:underline"
              >
                Reset All Filters
              </button>
            </div>

            {/* Registrations Filters */}
            {exportType === 'registrations' && (
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div>
                  <label className="block text-slate-600 font-semibold mb-1">
                    COURSE / PROGRAM
                  </label>
                  <select
                    value={regCourseFilter}
                    onChange={e => setRegCourseFilter(e.target.value)}
                    className="w-full p-2 bg-white border border-slate-300 rounded-lg text-slate-800 text-xs focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                  >
                    <option value="all">All Academic Courses ({courses.length})</option>
                    {courses.map(c => (
                      <option key={c.code} value={c.code}>
                        {c.code} – {c.name}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-slate-600 font-semibold mb-1">
                    ADMISSION STATUS
                  </label>
                  <select
                    value={regStatusFilter}
                    onChange={e => setRegStatusFilter(e.target.value)}
                    className="w-full p-2 bg-white border border-slate-300 rounded-lg text-slate-800 text-xs focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                  >
                    <option value="all">All Statuses (Approved & Pending)</option>
                    <option value="Approved">Approved (Admitted)</option>
                    <option value="Pending Verification">Pending Verification</option>
                    <option value="Rejected">Rejected</option>
                  </select>
                </div>

                <div>
                  <label className="block text-slate-600 font-semibold mb-1">
                    STUDY MODE
                  </label>
                  <select
                    value={regStudyModeFilter}
                    onChange={e => setRegStudyModeFilter(e.target.value)}
                    className="w-full p-2 bg-white border border-slate-300 rounded-lg text-slate-800 text-xs focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                  >
                    <option value="all">All Study Modes</option>
                    <option value="Day-Release">Day-Release</option>
                    <option value="Weekend">Weekend Only</option>
                  </select>
                </div>
              </div>
            )}

            {/* Attendance Filters */}
            {exportType === 'attendance' && (
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div>
                  <label className="block text-slate-600 font-semibold mb-1">
                    COURSE / MODULE
                  </label>
                  <select
                    value={attCourseFilter}
                    onChange={e => setAttCourseFilter(e.target.value)}
                    className="w-full p-2 bg-white border border-slate-300 rounded-lg text-slate-800 text-xs focus:ring-2 focus:ring-blue-500 focus:outline-none"
                  >
                    <option value="all">All Courses ({courses.length})</option>
                    {courses.map(c => (
                      <option key={c.code} value={c.code}>
                        {c.code} – {c.name}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-slate-600 font-semibold mb-1">
                    ATTENDANCE STATUS
                  </label>
                  <select
                    value={attStatusFilter}
                    onChange={e => setAttStatusFilter(e.target.value)}
                    className="w-full p-2 bg-white border border-slate-300 rounded-lg text-slate-800 text-xs focus:ring-2 focus:ring-blue-500 focus:outline-none"
                  >
                    <option value="all">All Records (Present, Absent, Late)</option>
                    <option value="Present">Present Only</option>
                    <option value="Absent">Absent Only (Audit Warnings)</option>
                    <option value="Late">Late Only</option>
                    <option value="Excused">Excused Only</option>
                  </select>
                </div>

                <div>
                  <label className="block text-slate-600 font-semibold mb-1">
                    SEARCH STUDENT ID / NAME
                  </label>
                  <input
                    type="text"
                    placeholder="e.g. STC/2026/ICT-108 or Banda"
                    value={attStudentSearch}
                    onChange={e => setAttStudentSearch(e.target.value)}
                    className="w-full p-2 bg-white border border-slate-300 rounded-lg text-slate-800 text-xs focus:ring-2 focus:ring-blue-500 focus:outline-none"
                  />
                </div>
              </div>
            )}

            {/* Consolidated Audit Info */}
            {exportType === 'consolidated' && (
              <div className="p-3 bg-purple-50/60 border border-purple-200 rounded-lg text-purple-900">
                <div className="font-semibold text-xs flex items-center gap-1.5 mb-1">
                  <ShieldCheck className="w-4 h-4 text-purple-700" />
                  <span>Comprehensive Regulatory Audit Sheet (TEVETA & Ministry of Education)</span>
                </div>
                <p className="text-[11px] leading-relaxed text-purple-800">
                  This report automatically computes each student's attendance percentage, validates National Bank fee clearance, and cross-references academic grade averages to verify final examination eligibility.
                </p>
              </div>
            )}

            {/* Date Range Inputs */}
            {exportType !== 'consolidated' && (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-slate-200">
                <div>
                  <label className="block text-slate-600 font-semibold mb-1">
                    START DATE (OPTIONAL)
                  </label>
                  <div className="relative">
                    <Calendar className="w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-2.5" />
                    <input
                      type="date"
                      value={startDate}
                      onChange={e => setStartDate(e.target.value)}
                      className="w-full pl-8 pr-2 py-1.5 bg-white border border-slate-300 rounded-lg text-slate-800 text-xs focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-slate-600 font-semibold mb-1">
                    END DATE (OPTIONAL)
                  </label>
                  <div className="relative">
                    <Calendar className="w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-2.5" />
                    <input
                      type="date"
                      value={endDate}
                      onChange={e => setEndDate(e.target.value)}
                      className="w-full pl-8 pr-2 py-1.5 bg-white border border-slate-300 rounded-lg text-slate-800 text-xs focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                    />
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Audit Metrics & Summary Badge */}
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 p-3.5 bg-slate-900 text-white rounded-xl">
            <div className="space-y-0.5">
              <div className="flex items-center gap-2">
                <span className="font-mono text-emerald-400 font-bold text-sm">
                  {exportResult.count} {exportResult.count === 1 ? 'Record' : 'Records'} Matched
                </span>
                <span className="text-slate-400 text-xs">• File:</span>
                <span className="font-mono text-slate-200 text-xs font-medium truncate max-w-xs sm:max-w-md">
                  {exportResult.filename}
                </span>
              </div>
              <p className="text-[11px] text-slate-400">
                Soche Technical College • Registrar & Bursar Audit Portal • Blantyre, Malawi
              </p>
            </div>

            <div className="flex items-center gap-2 shrink-0">
              <button
                type="button"
                onClick={handleCopyClipboard}
                className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 rounded-lg font-semibold text-xs flex items-center gap-1.5 transition"
              >
                {copiedSuccess ? (
                  <>
                    <Check className="w-3.5 h-3.5 text-emerald-400" />
                    <span>Copied!</span>
                  </>
                ) : (
                  <>
                    <Copy className="w-3.5 h-3.5" />
                    <span>Copy Raw CSV</span>
                  </>
                )}
              </button>

              <button
                type="button"
                onClick={handleDownload}
                className="px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white font-bold rounded-lg text-xs flex items-center gap-2 shadow-md active:scale-95 transition"
              >
                {downloadSuccess ? (
                  <>
                    <CheckCircle2 className="w-4 h-4 text-white" />
                    <span>Downloaded!</span>
                  </>
                ) : (
                  <>
                    <Download className="w-4 h-4" />
                    <span>Download CSV File</span>
                  </>
                )}
              </button>
            </div>
          </div>

          {/* Live Data Preview Accordion/Table */}
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Table className="w-4 h-4 text-slate-600" />
                <span className="font-bold text-slate-800 text-xs">
                  Dataset Sample Preview (First 5 Rows of {exportResult.count}):
                </span>
              </div>
              <button
                type="button"
                onClick={() => setShowPreviewTable(!showPreviewTable)}
                className="text-[11px] text-slate-500 hover:text-slate-800 font-medium"
              >
                {showPreviewTable ? 'Hide Preview' : 'Show Preview'}
              </button>
            </div>

            {showPreviewTable && (
              <div className="border border-slate-200 rounded-xl overflow-hidden shadow-2xs">
                <div className="overflow-x-auto max-h-56">
                  {previewHeaders.length > 0 ? (
                    <table className="w-full text-left text-[11px] border-collapse">
                      <thead>
                        <tr className="bg-slate-100 text-slate-700 font-bold border-b border-slate-200 whitespace-nowrap">
                          {previewHeaders.map((header, idx) => (
                            <th key={idx} className="p-2.5 border-r border-slate-200 last:border-r-0">
                              {header}
                            </th>
                          ))}
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-200">
                        {previewRows.map((row, rIdx) => (
                          <tr key={rIdx} className="hover:bg-slate-50 whitespace-nowrap font-mono text-[10px]">
                            {row.map((cell, cIdx) => (
                              <td key={cIdx} className="p-2 border-r border-slate-200 last:border-r-0 text-slate-700">
                                {cell || '-'}
                              </td>
                            ))}
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  ) : (
                    <div className="p-6 text-center text-slate-500 text-xs">
                      No records matched current filter criteria.
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Compliance & Local Filing Guidance Note */}
          <div className="p-3 bg-slate-100 rounded-xl border border-slate-200 flex items-start gap-2.5 text-slate-600 text-[11px]">
            <Building className="w-4 h-4 text-slate-500 shrink-0 mt-0.5" />
            <div>
              <span className="font-bold text-slate-800 block">
                Local Filing & Compliance Standard:
              </span>
              <span>
                Generated files adhere to RFC 4180 standard with standard UTF-8 Byte Order Mark (BOM). Files can be immediately opened in Microsoft Excel, Google Sheets, or imported into Malawi TEVETA / MoEST central management databases.
              </span>
            </div>
          </div>

        </div>

        {/* Modal Footer */}
        <div className="px-6 py-3.5 bg-slate-50 border-t border-slate-200 flex items-center justify-between shrink-0">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 bg-white hover:bg-slate-100 text-slate-700 border border-slate-300 font-semibold rounded-lg text-xs transition"
          >
            Close Window
          </button>

          <button
            type="button"
            onClick={handleDownload}
            className="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg text-xs flex items-center gap-2 shadow-sm active:scale-95 transition"
          >
            <Download className="w-4 h-4" />
            Download {exportType === 'registrations' ? 'Admissions CSV' : exportType === 'attendance' ? 'Attendance CSV' : 'Audit Master CSV'}
          </button>
        </div>

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