import { useState, useEffect } from 'react';
import { useAssignmentStore, Assignment } from '../../store/assignments';
import {
  BookOpen, Clock, CheckCircle, AlertTriangle, FileText,
  Save, Send, Eye, ChevronRight, Calendar, Award, X,
  Search, Filter, Sparkles, TrendingUp, Inbox,
  Download, Upload, CheckCircle2, Info, MoreHorizontal, Printer
} from 'lucide-react';

type TabType = 'pending' | 'in_progress' | 'completed';

export default function Assignments() {
  const [activeTab, setActiveTab] = useState<TabType>('pending');
  const [selectedAssignment, setSelectedAssignment] = useState<Assignment | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [draftContent, setDraftContent] = useState('');
  const [selectedFile, setSelectedFile] = useState<{ name: string; data: string } | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');

  const {
    assignments,
    submissions,
    isLoading,
    fetchAssignments,
    submitAssignment,
    saveDraft,
    loadDraft,
    getTimeRemaining,
    isOverdue,
  } = useAssignmentStore();

  useEffect(() => {
    fetchAssignments();
  }, [fetchAssignments]);

  // Load draft when opening an assignment
  useEffect(() => {
    if (selectedAssignment) {
      const draft = loadDraft(selectedAssignment.id);
      if (draft) {
        setDraftContent(draft.content);
        if (draft.file_name && draft.file_data) {
          setSelectedFile({ name: draft.file_name, data: draft.file_data });
        }
      } else {
        setDraftContent('');
        setSelectedFile(null);
      }
    }
  }, [selectedAssignment, loadDraft]);

  const handleStartAssignment = (assignment: Assignment) => {
    setSelectedAssignment(assignment);
    setIsModalOpen(true);
  };

  const handleSaveDraft = () => {
    if (selectedAssignment) {
      saveDraft(selectedAssignment.id, draftContent, selectedFile || undefined);
      alert('Draft progress saved to local storage.');
    }
  };

  const handleSubmit = async () => {
    if (!selectedAssignment) return;

    setIsSubmitting(true);
    try {
      await submitAssignment(selectedAssignment.id, {
        content: draftContent,
        file_name: selectedFile?.name,
        file_data: selectedFile?.data,
      });
      setIsModalOpen(false);
      setSelectedAssignment(null);
      setDraftContent('');
      setSelectedFile(null);
      fetchAssignments();
    } catch (err) {
      console.error('Failed to transmit submission:', err);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = () => {
        const base64 = (reader.result as string).split(',')[1];
        setSelectedFile({ name: file.name, data: base64 });
      };
      reader.readAsDataURL(file);
    }
  };

  const getFilteredAssignments = (): Assignment[] => {
    let filtered = assignments;

    if (activeTab === 'pending') {
      filtered = assignments.filter(a => a.status === 'pending');
    } else if (activeTab === 'in_progress') {
      filtered = assignments.filter(a => a.status === 'in_progress');
    } else {
      filtered = assignments.filter(a => a.status === 'completed' || a.status === 'graded');
    }

    if (searchTerm) {
      filtered = filtered.filter(a =>
        a.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        a.subject.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    return filtered;
  };

  const getAssignmentSubmission = (assignmentId: number) => {
    return submissions.find(s => s.assignment_id === assignmentId);
  };

  const getStatusStyles = (assignment: Assignment) => {
    const overdue = isOverdue(assignment.due_date) && assignment.status !== 'completed' && assignment.status !== 'graded';
    const draft = loadDraft(assignment.id);

    if (overdue) return { label: 'Overdue', color: 'text-rose-600', bg: 'bg-rose-50 dark:bg-rose-950/30', border: 'border-rose-100 dark:border-rose-900/30', icon: AlertTriangle };
    if (draft) return { label: 'In Draft', color: 'text-amber-600', bg: 'bg-amber-50 dark:bg-amber-950/30', border: 'border-amber-100 dark:border-amber-900/30', icon: Clock };

    switch (assignment.status) {
      case 'pending': return { label: 'Pending', color: 'text-blue-600 dark:text-blue-400', bg: 'bg-blue-50 dark:bg-blue-950/30', border: 'border-blue-100 dark:border-blue-900/30', icon: Inbox };
      case 'in_progress': return { label: 'In Progress', color: 'text-primary', bg: 'bg-primary/5', border: 'border-primary/20', icon: Clock };
      case 'completed': return { label: 'Submitted', color: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50 dark:bg-emerald-950/30', border: 'border-emerald-100 dark:border-emerald-900/30', icon: CheckCircle2 };
      case 'graded': return { label: 'Graded', color: 'text-purple-600 dark:text-purple-400', bg: 'bg-purple-50 dark:bg-purple-950/30', border: 'border-purple-100 dark:border-purple-900/30', icon: Award };
      default: return { label: assignment.status, color: 'text-text-muted', bg: 'bg-muted', border: 'border-border', icon: Info };
    }
  };

  const counts = {
    pending: assignments.filter(a => a.status === 'pending').length,
    in_progress: assignments.filter(a => a.status === 'in_progress').length,
    completed: assignments.filter(a => a.status === 'completed' || a.status === 'graded').length,
  };

  const filteredAssignments = getFilteredAssignments();

  // Stats
  const totalAssignments = assignments.length;
  const completedCount = assignments.filter(a => a.status === 'completed' || a.status === 'graded').length;
  const overdueCount = assignments.filter(a => isOverdue(a.due_date) && a.status !== 'completed' && a.status !== 'graded').length;

  if (isLoading) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
      <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
      <p className="font-black uppercase tracking-[3px] text-[0.6rem]">Accessing Course locker...</p>
    </div>
  );

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight text-capitalize dark:text-white">Assignment Workspace</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Student Portal</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Work Queue</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted/50 transition-all shadow-sm active:scale-95">
            <Download size={18} />
            Archive Transcript
          </button>
        </div>
      </div>

      {/* Stats Bento Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {[
          { label: 'Total Tasks', value: totalAssignments, icon: FileText, color: 'blue', trend: 'Academic' },
          { label: 'Completed', value: completedCount, icon: CheckCircle2, color: 'emerald', trend: 'Verified' },
          { label: 'Overdue', value: overdueCount, icon: AlertTriangle, color: 'rose', trend: 'Critical' },
        ].map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-6 rounded-[2.5rem] shadow-sm relative overflow-hidden group hover:shadow-md transition-all">
            <div className="relative z-10 flex justify-between items-start mb-4">
              <div className={`p-3 rounded-2xl 
                ${stat.color === 'blue' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800' : 
                  stat.color === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' : 
                  'bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800'} 
                group-hover:scale-110 transition-transform border`}>
                <stat.icon size={24} />
              </div>
              <div className="text-[0.65rem] font-black px-3 py-1 bg-muted text-text-muted rounded-full border border-border uppercase tracking-widest">
                {stat.trend}
              </div>
            </div>
            <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-1">{stat.label}</p>
            <h3 className="text-3xl font-black text-text tracking-tighter">{stat.value}</h3>
          </div>
        ))}
      </div>

      {/* Control Bar */}
      <div className="bg-card border border-border rounded-[2rem] p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
        {/* Status Tabs */}
        <div className="flex p-1 bg-muted/50 rounded-2xl flex-1 min-w-0">
          {(['pending', 'in_progress', 'completed'] as TabType[]).map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`
                flex-1 px-6 py-3 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all
                ${activeTab === tab 
                  ? 'bg-card text-primary shadow-sm ring-1 ring-border' 
                  : 'text-text-muted hover:text-text'}
              `}
            >
              {tab.replace('_', ' ')}
              <span className="ml-2 opacity-50">{counts[tab]}</span>
            </button>
          ))}
        </div>

        {/* Search Bar */}
        <div className="relative group min-w-[300px]">
          <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
          <input 
            type="text" 
            className="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all"
            placeholder="Search tasks..."
            value={searchTerm}
            onChange={e => setSearchTerm(e.target.value)}
          />
        </div>
      </div>

      {/* Assignments List */}
      {filteredAssignments.length === 0 ? (
        <div className="py-32 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
          <Inbox size={64} className="mx-auto text-text-muted/20 mb-6" />
          <h3 className="text-2xl font-black text-text mb-2 uppercase tracking-tighter">Queue Clear</h3>
          <p className="text-text-muted font-medium max-w-xs mx-auto">No {activeTab.replace('_', ' ')} assignments identified in your registry.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-4">
          {filteredAssignments.map((assignment) => {
            const styles = getStatusStyles(assignment);
            const submission = getAssignmentSubmission(assignment.id);
            const timeLeft = getTimeRemaining(assignment.due_date);

            return (
              <div key={assignment.id} className="bg-card border border-border rounded-[2.5rem] p-8 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative overflow-hidden">
                <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-8">
                  <div className="flex items-start gap-6 flex-1 min-w-0">
                    <div className="w-16 h-16 rounded-2xl bg-muted dark:bg-muted/20 flex items-center justify-center text-primary dark:text-blue-400 border border-border shadow-inner group-hover:scale-110 transition-transform">
                      <FileText size={28} />
                    </div>

                    <div className="space-y-1">
                      <h3 className="text-xl font-black text-text tracking-tight group-hover:text-primary transition-colors truncate">{assignment.title}</h3>
                      <p className="text-[0.65rem] font-black text-primary dark:text-blue-400 uppercase tracking-[3px]">{assignment.subject}</p>

                      <div className="flex flex-wrap items-center gap-6 mt-4">
                        <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-lg text-[0.65rem] font-black uppercase tracking-widest border ${styles.bg} ${styles.color} ${styles.border}`}>
                          <styles.icon size={12} />
                          {styles.label}
                        </span>

                        <span className="flex items-center gap-2 text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">
                          <Clock size={14} className="text-text-muted/50" />
                          {timeLeft}
                        </span>

                        <span className="flex items-center gap-2 text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">
                          <Calendar size={14} className="text-text-muted/50" />
                          Due: {new Date(assignment.due_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                        </span>

                        <span className="flex items-center gap-2 text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">
                          <Award size={14} className="text-text-muted/50" />
                          {assignment.total_marks} Marks
                        </span>
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center gap-3 w-full lg:w-auto shrink-0">
                    {activeTab === 'pending' && (
                      <button
                        onClick={() => handleStartAssignment(assignment)}
                        className="w-full lg:w-auto px-8 py-4 bg-primary hover:bg-primary/90 text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-lg active:scale-95 flex items-center justify-center gap-2 group/btn"
                      >
                        Start Module
                        <ChevronRight size={18} className="group-hover/btn:translate-x-1 transition-transform" />
                      </button>
                    )}

                    {activeTab === 'in_progress' && (
                      <button
                        onClick={() => handleStartAssignment(assignment)}
                        className="w-full lg:w-auto px-8 py-4 bg-primary hover:bg-primary/90 text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-lg active:scale-95 flex items-center justify-center gap-2 group/btn"
                      >
                        Continue Work
                        <ChevronRight size={18} className="group-hover/btn:translate-x-1 transition-transform" />
                      </button>
                    )}

                    {activeTab === 'completed' && (
                      <div className="flex items-center gap-2">
                        {submission?.feedback && (
                            <button
                                onClick={() => {
                                    setSelectedAssignment(assignment);
                                    setDraftContent(submission.feedback || '');
                                    setIsModalOpen(true);
                                }}
                                className="px-6 py-4 bg-purple-50 text-purple-600 border border-purple-100 rounded-2xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-purple-100 transition-all flex items-center gap-2"
                            >
                                <Eye size={16} />
                                View Critique
                            </button>
                        )}
                        <div className="px-6 py-4 bg-emerald-50 text-emerald-600 border border-emerald-100 rounded-2xl font-black text-[0.65rem] uppercase tracking-widest flex items-center gap-2 shadow-sm">
                          <CheckCircle2 size={16} />
                          {submission?.marks !== undefined ? `Result: ${submission.marks}/${assignment.total_marks}` : 'Transmitted'}
                        </div>
                      </div>
                    )}
                    
                    <button className="p-4 bg-muted hover:bg-muted/80 text-text-muted/50 hover:text-primary rounded-2xl border border-border transition-all">
                        <MoreHorizontal size={20} />
                    </button>
                  </div>
                </div>

                {assignment.description && (
                  <div className="mt-8 pl-[5rem] relative">
                    <div className="absolute left-[2.5rem] top-0 bottom-0 w-1 bg-border rounded-full"></div>
                    <p className="text-[0.9rem] text-text-muted font-medium leading-relaxed italic line-clamp-2">"{assignment.description}"</p>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* Submission Modal */}
      {isModalOpen && selectedAssignment && (
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[150] flex items-center justify-center p-4">
          <div className="bg-card rounded-[3rem] w-full max-w-4xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 max-h-[90vh] flex flex-col border border-border">
            {/* Modal Header */}
            <div className="p-10 pb-8 bg-muted/50 border-b border-border flex items-center justify-between shrink-0 relative overflow-hidden">
                <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                    <Sparkles size={180} />
                </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight">{selectedAssignment.title}</h2>
                <p className="text-[0.65rem] font-black text-primary uppercase tracking-[3px] mt-1">{selectedAssignment.subject} • Target: {new Date(selectedAssignment.due_date).toLocaleDateString()}</p>
              </div>
              <button
                onClick={() => {
                  setIsModalOpen(false);
                  setSelectedAssignment(null);
                  setDraftContent('');
                  setSelectedFile(null);
                }}
                className="relative z-10 w-12 h-12 flex items-center justify-center rounded-2xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm"
              >
                <X size={24} />
              </button>
            </div>

            {/* Modal Body */}
            <div className="p-10 overflow-y-auto flex-1 custom-scrollbar">
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-10">
                {/* Info Column */}
                <div className="space-y-8">
                    {selectedAssignment.instructions && (
                        <div className="space-y-3">
                            <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Instructions</h4>
                            <div className="p-6 bg-blue-50/10 dark:bg-blue-900/20 border border-blue-100/20 dark:border-blue-800/30 rounded-3xl">
                                <p className="text-[0.85rem] text-text-secondary font-medium leading-relaxed">{selectedAssignment.instructions}</p>
                            </div>
                        </div>
                    )}
                    
                    <div className="space-y-3">
                        <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Module Requirements</h4>
                        <div className="bg-muted/50 dark:bg-muted/20 border border-border rounded-3xl p-6 space-y-4 shadow-inner">
                            <div className="flex justify-between items-center">
                                <span className="text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">Time Remaining</span>
                                <span className={`text-[0.7rem] font-black uppercase ${isOverdue(selectedAssignment.due_date) ? 'text-rose-600' : 'text-primary'}`}>{getTimeRemaining(selectedAssignment.due_date)}</span>
                            </div>
                            <div className="flex justify-between items-center border-t border-border dark:border-blue-800/30 pt-4">
                                <span className="text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">Max Score</span>
                                <span className="text-[0.7rem] font-black uppercase text-text">{selectedAssignment.total_marks} Marks</span>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Editor Column */}
                <div className="lg:col-span-2 space-y-8">
                    <div className="space-y-3">
                        <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Student Response</h4>
                        <textarea
                            value={draftContent}
                            onChange={(e) => setDraftContent(e.target.value)}
                            placeholder="Initialize response here..."
                            className="w-full h-80 p-8 bg-muted/50 border border-border rounded-[2.5rem] resize-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-[0.95rem] font-medium leading-relaxed shadow-inner placeholder:text-text-muted/30"
                        />
                    </div>

                    <div className="space-y-3">
                        <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Material Assets</h4>
                        <div 
                            className="border-2 border-dashed border-border rounded-3xl p-8 text-center hover:border-primary hover:bg-blue-50/10 transition-all cursor-pointer group"
                            onClick={() => document.getElementById('file-upload')?.click()}
                        >
                            <input
                                id="file-upload"
                                type="file"
                                onChange={handleFileChange}
                                className="hidden"
                            />
                            {selectedFile ? (
                                <div className="flex items-center justify-center gap-3">
                                    <div className="p-2 bg-primary/10 rounded-lg text-primary">
                                        <FileText size={20} />
                                    </div>
                                    <span className="text-sm font-bold text-text">{selectedFile.name}</span>
                                    <button onClick={(e) => { e.stopPropagation(); setSelectedFile(null); }} className="p-1 hover:bg-rose-50 text-rose-500 rounded-lg transition-all"><X size={16} /></button>
                                </div>
                            ) : (
                                <div className="flex flex-col items-center gap-2">
                                    <Upload className="text-text-muted/30 group-hover:text-primary transition-colors" size={32} />
                                    <p className="text-sm font-bold text-text-muted group-hover:text-text transition-colors">Attach submission assets</p>
                                    <p className="text-[0.6rem] font-bold text-text-muted/30 uppercase tracking-widest">PDF, DOCX, or ZIP allowed</p>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
              </div>
            </div>

            {/* Modal Footer */}
            <div className="p-10 border-t border-border flex flex-col sm:flex-row justify-between gap-4 shrink-0 bg-muted/50">
              <button
                onClick={() => {
                  setIsModalOpen(false);
                  setSelectedAssignment(null);
                }}
                className="px-10 py-4 bg-card border border-border text-text-muted rounded-2xl font-black text-[0.7rem] uppercase tracking-widest hover:bg-muted transition-all"
              >
                Exit Workspace
              </button>

              <div className="flex gap-3">
                <button
                  onClick={handleSaveDraft}
                  className="flex-1 sm:flex-none px-10 py-4 bg-card border border-primary/20 text-primary rounded-2xl font-black text-[0.7rem] uppercase tracking-widest hover:bg-blue-50/10 transition-all shadow-sm flex items-center justify-center gap-2"
                >
                  <Save size={18} />
                  Save Draft
                </button>
                <button
                  onClick={handleSubmit}
                  disabled={isSubmitting || (!draftContent.trim() && !selectedFile)}
                  className="flex-1 sm:flex-none px-12 py-4 bg-primary hover:bg-primary-dark text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-xl active:scale-95 disabled:opacity-50 disabled:grayscale flex items-center justify-center gap-2 group/submit"
                >
                  {isSubmitting ? <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" /> : <Send size={18} className="group-hover/submit:translate-x-1 group-hover/submit:-translate-y-1 transition-transform" />}
                  {isSubmitting ? 'Transmitting...' : 'Submit Module'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
      `}</style>
    </div>
  );
}
