import React, { useState, useEffect } from 'react';
import {
  X,
  FileCheck,
  ShieldCheck,
  AlertTriangle,
  Download,
  ExternalLink,
  Layers,
  Search,
  CheckCircle2,
  Clock,
  Sparkles,
  Info,
} from 'lucide-react';
import { RECONCILIATION_REPORT, ReconciliationEntry } from '../data/catalogueData';
import { ALL_COURSES } from '../data/allCourses';
import { ZiteCourse } from '../data/courses';

interface CurriculumGovernanceModalProps {
  isOpen: boolean;
  onClose: () => void;
  onRequestOutline?: (course: ZiteCourse) => void;
}

export function CurriculumGovernanceModal({
  isOpen,
  onClose,
  onRequestOutline,
}: CurriculumGovernanceModalProps) {
  const [activeTab, setActiveTab] = useState<'inventory' | 'reconciliation' | 'integration'>('inventory');
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'approved' | 'draft'>('all');

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [isOpen]);

  if (!isOpen) return null;

  const approvedCourses = ALL_COURSES.filter((c) => c.publicationStatus === 'approved');
  const draftCourses = ALL_COURSES.filter((c) => c.publicationStatus === 'draft');

  const filteredInventory = ALL_COURSES.filter((c) => {
    const matchesStatus =
      statusFilter === 'all' ||
      (statusFilter === 'approved' && c.publicationStatus === 'approved') ||
      (statusFilter === 'draft' && c.publicationStatus === 'draft');

    const matchesQuery =
      !searchQuery.trim() ||
      `${c.id} ${c.title} ${c.provider} ${c.category} ${c.level} ${c.sourceCatalogueId}`
        .toLowerCase()
        .includes(searchQuery.toLowerCase());

    return matchesStatus && matchesQuery;
  });

  const filteredReconciliation = RECONCILIATION_REPORT.filter((r) => {
    if (!searchQuery.trim()) return true;
    return `${r.candidateId} ${r.paniaTitle} ${r.status} ${r.existingMatch} ${r.reason}`
      .toLowerCase()
      .includes(searchQuery.toLowerCase());
  });

  return (
    <div
      className="fixed inset-0 z-50 overflow-y-auto bg-black/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-6"
      role="dialog"
      aria-modal="true"
      aria-labelledby="governance-modal-title"
    >
      <div className="bg-card w-full max-w-5xl rounded-3xl border border-border shadow-2xl overflow-hidden flex flex-col max-h-[92vh] outline-hidden animate-in fade-in zoom-in-95 duration-200">
        {/* Header */}
        <div className="p-6 border-b border-border bg-[#0B4035] text-white flex items-start justify-between gap-4">
          <div>
            <div className="flex items-center gap-2">
              <span className="inline-flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider bg-[#D5E64D] text-[#072C24] px-2.5 py-0.5 rounded-full">
                <FileCheck className="h-3.5 w-3.5" />
                <span>Academic Governance & Course Reconciliation</span>
              </span>
              <span className="text-xs font-semibold px-2.5 py-0.5 rounded-full bg-white/15 text-white">
                Catalogue Total: {ALL_COURSES.length} Programmes
              </span>
            </div>
            <h2 id="governance-modal-title" className="text-xl sm:text-2xl font-bold mt-2 text-white">
              Curriculum Integrity & PDF Outline Inventory
            </h2>
            <p className="text-xs text-white/80 mt-0.5">
              Strict reconciliation between PANIA canonical courses (C01–C22) and candidate vendor tracks.
            </p>
          </div>

          <button
            onClick={onClose}
            aria-label="Close governance modal"
            className="p-2 rounded-full hover:bg-white/10 text-white/80 hover:text-white transition cursor-pointer"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Tab Navigation & Search Bar */}
        <div className="px-6 py-3 bg-secondary/50 border-b border-border flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3">
          <div className="flex items-center gap-1.5 overflow-x-auto pb-1 sm:pb-0">
            <button
              onClick={() => setActiveTab('inventory')}
              className={`px-3.5 py-1.5 rounded-xl text-xs font-bold transition cursor-pointer whitespace-nowrap ${
                activeTab === 'inventory'
                  ? 'bg-primary text-primary-foreground shadow-2xs'
                  : 'text-muted-foreground hover:text-foreground'
              }`}
            >
              PDF Outline Inventory ({ALL_COURSES.length})
            </button>
            <button
              onClick={() => setActiveTab('reconciliation')}
              className={`px-3.5 py-1.5 rounded-xl text-xs font-bold transition cursor-pointer whitespace-nowrap ${
                activeTab === 'reconciliation'
                  ? 'bg-primary text-primary-foreground shadow-2xs'
                  : 'text-muted-foreground hover:text-foreground'
              }`}
            >
              Reconciliation Matrix ({RECONCILIATION_REPORT.length})
            </button>
            <button
              onClick={() => setActiveTab('integration')}
              className={`px-3.5 py-1.5 rounded-xl text-xs font-bold transition cursor-pointer whitespace-nowrap ${
                activeTab === 'integration'
                  ? 'bg-primary text-primary-foreground shadow-2xs'
                  : 'text-muted-foreground hover:text-foreground'
              }`}
            >
              Admissions & Email API
            </button>
          </div>

          {/* Search Box */}
          <div className="relative w-full sm:w-64">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
            <input
              type="text"
              placeholder="Search by code, title, track..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-8 pr-3 py-1.5 text-xs rounded-xl border border-border bg-background text-foreground placeholder:text-muted-foreground focus:outline-hidden focus:ring-2 focus:ring-primary"
            />
          </div>
        </div>

        {/* Tab Content Body */}
        <div className="p-6 overflow-y-auto space-y-6 flex-1 text-xs">
          {/* TAB 1: PDF OUTLINE INVENTORY */}
          {activeTab === 'inventory' && (
            <div className="space-y-4">
              {/* Summary Metrics */}
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div className="p-3.5 rounded-2xl bg-card border border-border shadow-xs">
                  <div className="flex items-center gap-2 text-primary font-bold">
                    <ShieldCheck className="h-4 w-4" />
                    <span>Academically Approved</span>
                  </div>
                  <p className="text-xl font-bold mt-1 text-foreground">{approvedCourses.length} Programmes</p>
                  <p className="text-[11px] text-muted-foreground mt-0.5">
                    Original PANIA C01–C22 catalogue. Vector PDF outlines available on enquiry.
                  </p>
                </div>

                <div className="p-3.5 rounded-2xl bg-card border border-border shadow-xs">
                  <div className="flex items-center gap-2 text-amber-600 font-bold">
                    <Clock className="h-4 w-4" />
                    <span>Candidate Drafts</span>
                  </div>
                  <p className="text-xl font-bold mt-1 text-foreground">{draftCourses.length} In Review</p>
                  <p className="text-[11px] text-muted-foreground mt-0.5">
                    Curricula drafted; pending academic faculty sign-off before public download release.
                  </p>
                </div>

                <div className="p-3.5 rounded-2xl bg-card border border-border shadow-xs">
                  <div className="flex items-center gap-2 text-teal font-bold">
                    <Layers className="h-4 w-4" />
                    <span>Format & Layout</span>
                  </div>
                  <p className="text-xl font-bold mt-1 text-foreground">A4 Portrait (2-3pp)</p>
                  <p className="text-[11px] text-muted-foreground mt-0.5">
                    PANIA Green (#0B4035) & Citron (#D5E64D), official logo, module breakdown, capstone.
                  </p>
                </div>
              </div>

              {/* Status Filter Toggle */}
              <div className="flex items-center gap-2 pt-2">
                <span className="font-bold text-muted-foreground">Filter by status:</span>
                <button
                  onClick={() => setStatusFilter('all')}
                  className={`px-2.5 py-1 rounded-lg text-xs font-semibold cursor-pointer ${
                    statusFilter === 'all' ? 'bg-primary text-primary-foreground' : 'bg-secondary text-muted-foreground'
                  }`}
                >
                  All ({ALL_COURSES.length})
                </button>
                <button
                  onClick={() => setStatusFilter('approved')}
                  className={`px-2.5 py-1 rounded-lg text-xs font-semibold cursor-pointer ${
                    statusFilter === 'approved' ? 'bg-emerald-600 text-white' : 'bg-secondary text-muted-foreground'
                  }`}
                >
                  Approved Only ({approvedCourses.length})
                </button>
                <button
                  onClick={() => setStatusFilter('draft')}
                  className={`px-2.5 py-1 rounded-lg text-xs font-semibold cursor-pointer ${
                    statusFilter === 'draft' ? 'bg-amber-600 text-white' : 'bg-secondary text-muted-foreground'
                  }`}
                >
                  Drafts Only ({draftCourses.length})
                </button>
              </div>

              {/* Table of PDF Inventory */}
              <div className="rounded-2xl border border-border overflow-hidden">
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-xs">
                    <thead className="bg-secondary/70 text-foreground font-bold border-b border-border">
                      <tr>
                        <th className="p-3">Ref ID</th>
                        <th className="p-3">Programme Title</th>
                        <th className="p-3">Track / Category</th>
                        <th className="p-3">Level</th>
                        <th className="p-3">Doc Version</th>
                        <th className="p-3">Publication Status</th>
                        <th className="p-3 text-right">Action</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border/60 bg-card">
                      {filteredInventory.map((c) => (
                        <tr key={c.id} className="hover:bg-secondary/30 transition-colors">
                          <td className="p-3 font-mono font-bold text-primary">{c.id}</td>
                          <td className="p-3 font-semibold text-foreground">
                            <div>{c.title}</div>
                            <div className="text-[10px] text-muted-foreground font-mono">{c.outlineFileKey}</div>
                          </td>
                          <td className="p-3 text-muted-foreground">
                            <span className="font-medium text-foreground">{c.provider}</span> · {c.category}
                          </td>
                          <td className="p-3 text-muted-foreground">{c.level}</td>
                          <td className="p-3 font-mono">{c.outlineVersion}</td>
                          <td className="p-3">
                            {c.publicationStatus === 'approved' ? (
                              <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-emerald-500/10 text-emerald-700">
                                <CheckCircle2 className="h-3 w-3" />
                                <span>Approved</span>
                              </span>
                            ) : (
                              <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-500/10 text-amber-700">
                                <Clock className="h-3 w-3" />
                                <span>Draft in Review</span>
                              </span>
                            )}
                          </td>
                          <td className="p-3 text-right">
                            <button
                              onClick={() => {
                                onClose();
                                if (onRequestOutline) {
                                  onRequestOutline({
                                    code: c.id,
                                    slug: c.slug,
                                    title: c.title,
                                    subject: c.category as any,
                                    provider: c.provider as any,
                                    headline: c.headline || [c.title, 'Practical mastery for real workplace impact.'],
                                    who: c.audience,
                                    outcomes: c.outcomes,
                                    practical: c.practicals,
                                    image: c.image || '',
                                    publicationStatus: c.publicationStatus,
                                  });
                                }
                              }}
                              className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-border bg-background hover:bg-secondary text-primary font-bold cursor-pointer"
                            >
                              <Download className="h-3 w-3" />
                              <span>{c.publicationStatus === 'approved' ? 'Request Outline' : 'Enquire Draft'}</span>
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* TAB 2: RECONCILIATION MATRIX */}
          {activeTab === 'reconciliation' && (
            <div className="space-y-4">
              <div className="p-4 rounded-2xl bg-secondary/50 border border-border space-y-1">
                <h4 className="font-bold text-sm text-foreground flex items-center gap-1.5">
                  <Info className="h-4 w-4 text-primary" />
                  <span>Curriculum Reconciliation Audit</span>
                </h4>
                <p className="text-muted-foreground leading-relaxed">
                  Every candidate course from C001–C169 was verified against PANIA&apos;s active curriculum. Existing courses (C01–C22) have been strictly retained with untouched IDs and URLs. Duplicate candidate tracks are aliased to PANIA courses, and genuinely missing tracks are onboarded into draft review.
                </p>
              </div>

              <div className="rounded-2xl border border-border overflow-hidden">
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-xs">
                    <thead className="bg-secondary/70 text-foreground font-bold border-b border-border">
                      <tr>
                        <th className="p-3">Candidate Ref</th>
                        <th className="p-3">Course Title</th>
                        <th className="p-3">Reconciliation Status</th>
                        <th className="p-3">PANIA Match</th>
                        <th className="p-3">Governance Rationale</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border/60 bg-card">
                      {filteredReconciliation.map((r) => (
                        <tr key={r.candidateId} className="hover:bg-secondary/30 transition-colors">
                          <td className="p-3 font-mono font-bold text-primary">{r.candidateId}</td>
                          <td className="p-3 font-semibold text-foreground">{r.paniaTitle}</td>
                          <td className="p-3">
                            {r.status === 'Retain' && (
                              <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-emerald-500/10 text-emerald-700">
                                <CheckCircle2 className="h-3 w-3" />
                                <span>Retain Existing</span>
                              </span>
                            )}
                            {r.status === 'Add' && (
                              <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-blue-500/10 text-blue-700">
                                <Sparkles className="h-3 w-3" />
                                <span>Add (Draft Review)</span>
                              </span>
                            )}
                            {r.status === 'Review' && (
                              <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-500/10 text-amber-700">
                                <AlertTriangle className="h-3 w-3" />
                                <span>Align with Active</span>
                              </span>
                            )}
                          </td>
                          <td className="p-3">
                            {r.existingMatch && r.existingMatch !== 'None' ? (
                              <span className="font-mono font-bold text-primary">
                                {r.existingMatch}
                              </span>
                            ) : (
                              <span className="text-muted-foreground italic">None (Candidate)</span>
                            )}
                          </td>
                          <td className="p-3 text-muted-foreground">{r.reason}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}

          {/* TAB 3: ADMISSIONS & PDF ENGINE */}
          {activeTab === 'integration' && (
            <div className="space-y-4">
              <div className="p-4 rounded-2xl bg-card border border-border shadow-xs space-y-3">
                <h4 className="font-bold text-sm text-foreground flex items-center gap-2">
                  <ShieldCheck className="h-4 w-4 text-primary" />
                  <span>Admissions Desk Registry & PDF Generator</span>
                </h4>
                <p className="text-muted-foreground leading-relaxed">
                  PANIA&apos;s full-stack Express server processes enquiries, records student interest with a unique tracking reference, and generates vector-sharp, publication-grade A4 PDF course outlines on demand.
                </p>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2">
                  <div className="p-3 rounded-xl bg-secondary/50 border border-border">
                    <span className="text-muted-foreground block text-[11px]">Admissions Desk Contact:</span>
                    <strong className="text-foreground font-mono">admissions@pania.co.ke</strong>
                    <span className="text-[10px] text-muted-foreground block mt-0.5">Official Student Inquiries</span>
                  </div>

                  <div className="p-3 rounded-xl bg-secondary/50 border border-border">
                    <span className="text-muted-foreground block text-[11px]">PDF Document Generation:</span>
                    <strong className="text-foreground">Vector A4 Landscape / Portrait</strong>
                    <span className="text-[10px] text-muted-foreground block mt-0.5">Dynamic Pagination & Watermarking</span>
                  </div>
                </div>

                <div className="p-3.5 rounded-xl bg-primary/10 border border-primary/20 text-foreground space-y-1">
                  <h5 className="font-bold text-primary flex items-center gap-1.5">
                    <CheckCircle2 className="h-4 w-4" />
                    <span>Direct Download Enabled</span>
                  </h5>
                  <p className="text-muted-foreground leading-relaxed text-xs">
                    Prospective students and corporate managers can immediately download official course outlines upon submitting their contact details. All enquiries are recorded in the admissions log.
                  </p>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-4 border-t border-border bg-secondary/40 flex items-center justify-between">
          <span className="text-xs text-muted-foreground">
            PANIA Digital Academy · Academic Governance Registry · Nairobi, Kenya
          </span>
          <button
            onClick={onClose}
            className="px-4 py-2 rounded-xl bg-primary text-primary-foreground font-bold text-xs hover:opacity-90 transition cursor-pointer"
          >
            Close Registry
          </button>
        </div>
      </div>
    </div>
  );
}
