import React, { useState } from 'react';
import { useCollege } from '../context/CollegeContext';
import {
  BookOpen,
  Download,
  Upload,
  Search,
  Filter,
  FileText,
  FileCheck,
  Calendar,
  CheckCircle2,
  FolderOpen,
  Plus,
} from 'lucide-react';
import confetti from 'canvas-confetti';

export const StudyHubView: React.FC = () => {
  const { studyMaterials, assignments, currentUser, submitAssignmentWork, uploadMaterial, courses } = useCollege();
  const [selectedCategory, setSelectedCategory] = useState<string>('All');
  const [searchTerm, setSearchTerm] = useState('');
  const [activeTab, setActiveTab] = useState<'materials' | 'assignments'>('materials');

  // Submissions State
  const [activeAsnId, setActiveAsnId] = useState<string | null>(null);
  const [submissionFile, setSubmissionFile] = useState('');
  const [submissionNotes, setSubmissionNotes] = useState('');

  // Upload Material State
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [uploadForm, setUploadForm] = useState({
    title: '',
    description: '',
    courseCode: 'CG1004',
    category: 'Lecture Notes' as const,
    fileType: 'PDF' as const,
    fileSize: '4.2 MB',
    examBoard: 'City and Guilds',
  });

  const categories = ['All', 'Lecture Notes', 'Past Exam Paper', 'Syllabus', 'Lab Manual'];

  const filteredMaterials = studyMaterials.filter(m => {
    if (selectedCategory !== 'All' && m.category !== selectedCategory) return false;
    if (searchTerm) {
      const match = `${m.title} ${m.courseCode} ${m.courseName} ${m.description}`.toLowerCase();
      if (!match.includes(searchTerm.toLowerCase())) return false;
    }
    return true;
  });

  const handleUploadSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const course = courses.find(c => c.code === uploadForm.courseCode);
    uploadMaterial({
      title: uploadForm.title,
      description: uploadForm.description,
      courseCode: uploadForm.courseCode,
      courseName: course ? course.name : 'Technical Diploma',
      category: uploadForm.category,
      fileType: uploadForm.fileType,
      fileSize: uploadForm.fileSize,
      examBoard: uploadForm.examBoard,
      uploadedBy: currentUser.name,
    });
    setShowUploadModal(false);
    try { confetti({ particleCount: 40, spread: 60 }); } catch (e) {}
  };

  const handleSubmitAssignment = (asnId: string) => {
    if (!submissionFile) {
      alert('Please specify the file name.');
      return;
    }
    submitAssignmentWork(asnId, {
      fileName: submissionFile,
      fileSize: '2.8 MB',
      notes: submissionNotes || 'Submitted online via STC Student Portal.',
    });
    setActiveAsnId(null);
    setSubmissionFile('');
    setSubmissionNotes('');
    try { confetti({ particleCount: 50, spread: 60 }); } catch (e) {}
  };

  return (
    <div className="space-y-6">
      
      {/* Header Banner */}
      <div className="bg-slate-900 text-white rounded-2xl p-6 shadow-md border border-slate-800 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="space-y-1">
          <div className="flex items-center gap-2">
            <span className="bg-emerald-500 text-slate-950 font-mono text-[10px] font-bold px-2 py-0.5 rounded uppercase">
              Cloud Repository & Learning Hub
            </span>
            <span className="text-xs text-slate-400">July 2026 Academic Archive</span>
          </div>
          <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-white">
            Study Materials, Past Exam Papers & Assignments
          </h1>
          <p className="text-xs sm:text-sm text-slate-300">
            Access accredited ICAM, City & Guilds, ABE, ABMA course texts, revision kits, and submit lab deliverables.
          </p>
        </div>

        {currentUser.role === 'teacher' || currentUser.role === 'admin' ? (
          <button
            onClick={() => setShowUploadModal(true)}
            className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold rounded-lg transition shadow flex items-center gap-1.5"
          >
            <Upload className="w-4 h-4" />
            Upload Study Material
          </button>
        ) : null}
      </div>

      {/* Tabs */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-xs overflow-hidden">
        <div className="flex border-b border-slate-200 bg-slate-50 px-6 pt-3 gap-4">
          <button
            onClick={() => setActiveTab('materials')}
            className={`pb-3 text-xs font-bold transition border-b-2 flex items-center gap-2 ${
              activeTab === 'materials'
                ? 'border-emerald-600 text-emerald-800'
                : 'border-transparent text-slate-500 hover:text-slate-900'
            }`}
          >
            <FolderOpen className="w-4 h-4" />
            Study Materials & Past Papers ({studyMaterials.length})
          </button>

          <button
            onClick={() => setActiveTab('assignments')}
            className={`pb-3 text-xs font-bold transition border-b-2 flex items-center gap-2 ${
              activeTab === 'assignments'
                ? 'border-emerald-600 text-emerald-800'
                : 'border-transparent text-slate-500 hover:text-slate-900'
            }`}
          >
            <FileCheck className="w-4 h-4" />
            Practical Labs & Assignments ({assignments.length})
          </button>
        </div>

        {/* Tab 1: Materials */}
        {activeTab === 'materials' && (
          <div className="p-4 sm:p-6 space-y-5">
            <div className="flex flex-col sm:flex-row gap-3 items-center justify-between">
              <div className="relative w-full sm:w-80">
                <Search className="w-4 h-4 text-slate-400 absolute left-3 top-2.5" />
                <input
                  type="text"
                  placeholder="Search lecture notes, past papers, syllabus..."
                  value={searchTerm}
                  onChange={e => setSearchTerm(e.target.value)}
                  className="w-full pl-9 pr-3 py-2 bg-slate-50 border border-slate-300 rounded-lg text-xs focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                />
              </div>

              <div className="flex gap-1 overflow-x-auto no-scrollbar w-full sm:w-auto">
                {categories.map(cat => (
                  <button
                    key={cat}
                    onClick={() => setSelectedCategory(cat)}
                    className={`px-3 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap transition ${
                      selectedCategory === cat
                        ? 'bg-slate-900 text-white'
                        : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
                    }`}
                  >
                    {cat}
                  </button>
                ))}
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {filteredMaterials.map(mat => (
                <div
                  key={mat.id}
                  className="border border-slate-200 rounded-xl p-4 bg-slate-50 flex flex-col justify-between space-y-3 text-xs"
                >
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <span className="px-2 py-0.5 bg-purple-100 text-purple-900 border border-purple-200 rounded text-[10px] font-bold">
                        {mat.category}
                      </span>
                      <span className="font-mono text-slate-500 text-[10px]">{mat.fileType} • {mat.fileSize}</span>
                    </div>

                    <h3 className="font-bold text-sm text-slate-900">{mat.title}</h3>
                    <p className="text-slate-600 text-[11px] leading-relaxed">{mat.description}</p>
                    <div className="text-[10px] text-emerald-800 font-semibold bg-emerald-50 px-2 py-1 rounded inline-block">
                      Course: {mat.courseCode} ({mat.examBoard})
                    </div>
                  </div>

                  <div className="flex items-center justify-between pt-2 border-t border-slate-200 text-[11px]">
                    <span className="text-slate-500 text-[10px]">Uploaded: {mat.uploadDate}</span>
                    <button
                      onClick={() => alert(`Downloading "${mat.title}" (${mat.fileSize})...`)}
                      className="px-3 py-1.5 bg-slate-900 hover:bg-slate-800 text-white font-semibold rounded text-xs flex items-center gap-1.5 shadow-xs"
                    >
                      <Download className="w-3.5 h-3.5 text-emerald-400" />
                      Download Material
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Tab 2: Assignments */}
        {activeTab === 'assignments' && (
          <div className="p-4 sm:p-6 space-y-4">
            <div className="grid grid-cols-1 gap-4">
              {assignments.map(asn => (
                <div
                  key={asn.id}
                  className="border border-slate-200 rounded-xl p-5 bg-slate-50 space-y-3 text-xs"
                >
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                    <div>
                      <span className="font-mono text-[10px] text-slate-500 font-bold block">{asn.courseCode}</span>
                      <h3 className="font-bold text-base text-slate-900">{asn.title}</h3>
                      <span className="text-slate-500 font-mono text-[11px]">Due: {asn.dueDate} • Total Marks: {asn.totalMarks}</span>
                    </div>

                    {asn.mySubmission ? (
                      <span className="bg-emerald-100 text-emerald-900 px-3 py-1 rounded-full font-bold text-[11px] border border-emerald-300 self-start">
                        {asn.mySubmission.status} {asn.mySubmission.score ? `(${asn.mySubmission.score}/${asn.totalMarks})` : ''}
                      </span>
                    ) : (
                      <button
                        onClick={() => setActiveAsnId(asn.id)}
                        className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg text-xs self-start"
                      >
                        Submit Assignment
                      </button>
                    )}
                  </div>

                  <p className="text-slate-700 leading-relaxed">{asn.instructions}</p>

                  {/* Submission detail */}
                  {asn.mySubmission && (
                    <div className="p-3.5 bg-white border border-slate-200 rounded-lg space-y-1.5">
                      <div className="flex justify-between font-semibold text-slate-800">
                        <span>Submitted File: {asn.mySubmission.fileName} ({asn.mySubmission.fileSize})</span>
                        <span className="text-slate-400 font-mono text-[10px]">{asn.mySubmission.submittedAt}</span>
                      </div>
                      <p className="text-slate-600 italic">Notes: "{asn.mySubmission.notes}"</p>
                      {asn.mySubmission.feedback && (
                        <div className="p-2 bg-emerald-50 border border-emerald-200 rounded text-emerald-900 font-medium">
                          <strong>Lecturer Feedback:</strong> {asn.mySubmission.feedback}
                        </div>
                      )}
                    </div>
                  )}

                  {/* Submit Box */}
                  {activeAsnId === asn.id && (
                    <div className="p-4 bg-white border-2 border-emerald-400 rounded-xl space-y-3 animate-in fade-in">
                      <h4 className="font-bold text-slate-900">Upload Project / Assignment Work</h4>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div>
                          <label className="block font-semibold text-slate-700 mb-1">FILE NAME</label>
                          <input
                            type="text"
                            placeholder="e.g. Kondwani_Banda_Accounting_IAS7.pdf"
                            value={submissionFile}
                            onChange={e => setSubmissionFile(e.target.value)}
                            className="w-full p-2 border border-slate-300 rounded text-xs font-mono"
                          />
                        </div>
                        <div>
                          <label className="block font-semibold text-slate-700 mb-1">SUBMISSION NOTES</label>
                          <input
                            type="text"
                            placeholder="Optional notes for lecturer..."
                            value={submissionNotes}
                            onChange={e => setSubmissionNotes(e.target.value)}
                            className="w-full p-2 border border-slate-300 rounded text-xs"
                          />
                        </div>
                      </div>

                      <div className="flex justify-end gap-2">
                        <button
                          onClick={() => setActiveAsnId(null)}
                          className="px-3 py-1.5 text-slate-600 hover:bg-slate-100 rounded text-xs"
                        >
                          Cancel
                        </button>
                        <button
                          onClick={() => handleSubmitAssignment(asn.id)}
                          className="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded text-xs shadow"
                        >
                          Confirm & Submit Deliverable
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Upload Material Modal */}
      {showUploadModal && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl max-w-md w-full p-6 space-y-4 border border-slate-200 animate-in fade-in">
            <h3 className="font-bold text-slate-900 text-base">
              Upload Study Material
            </h3>

            <form onSubmit={handleUploadSubmit} className="space-y-3 text-xs">
              <div>
                <label className="block font-semibold text-slate-700 mb-1">MATERIAL TITLE *</label>
                <input
                  type="text"
                  required
                  placeholder="e.g. Financial Accounting IFRS Standards"
                  value={uploadForm.title}
                  onChange={e => setUploadForm({ ...uploadForm, title: e.target.value })}
                  className="w-full p-2 border border-slate-300 rounded text-xs"
                />
              </div>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">COURSE</label>
                <select
                  value={uploadForm.courseCode}
                  onChange={e => setUploadForm({ ...uploadForm, courseCode: e.target.value })}
                  className="w-full p-2 border border-slate-300 rounded text-xs"
                >
                  {courses.map(c => (
                    <option key={c.code} value={c.code}>{c.code}: {c.name}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">CATEGORY</label>
                <select
                  value={uploadForm.category}
                  onChange={e => setUploadForm({ ...uploadForm, category: e.target.value as any })}
                  className="w-full p-2 border border-slate-300 rounded text-xs"
                >
                  <option value="Lecture Notes">Lecture Notes</option>
                  <option value="Past Exam Paper">Past Exam Paper</option>
                  <option value="Syllabus">Syllabus</option>
                  <option value="Lab Manual">Lab Manual</option>
                </select>
              </div>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">DESCRIPTION</label>
                <textarea
                  rows={2}
                  value={uploadForm.description}
                  onChange={e => setUploadForm({ ...uploadForm, description: e.target.value })}
                  className="w-full p-2 border border-slate-300 rounded text-xs"
                />
              </div>

              <div className="flex justify-end gap-2 pt-3">
                <button
                  type="button"
                  onClick={() => setShowUploadModal(false)}
                  className="px-4 py-2 text-slate-600 hover:bg-slate-100 rounded font-semibold"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-5 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded shadow"
                >
                  Upload File
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};
