'use client';

import DashboardLayout from '@/layouts/DashboardLayout';
import { DocumentTextIcon, ClockIcon, ExclamationTriangleIcon, CheckCircleIcon, CalendarIcon, XMarkIcon, PaperAirplaneIcon } from '@heroicons/react/24/outline';
import { cn } from '@/utils/cn';
import { useState } from 'react';

const assignments = [
  {
    id: 1,
    title: 'Analisis Kasus HACCP di Industri Makanan',
    course: 'HACCP - Hazard Analysis Critical Control Point',
    dueDate: '2024-01-30',
    submittedDate: null,
    status: 'pending',
    priority: 'high',
    points: 100,
    description: 'Buatlah analisis lengkap mengenai penerapan sistem HACCP pada industri makanan pilihan Anda.',
    attachments: ['template-analisis.docx'],
    timeRemaining: '5 hari'
  },
  {
    id: 2,
    title: 'Laporan Observasi Sanitasi Lingkungan',
    course: 'SLHS - Sanitasi Lingkungan Hidup Sehat',
    dueDate: '2024-02-05',
    submittedDate: null,
    status: 'pending',
    priority: 'medium',
    points: 80,
    description: 'Lakukan observasi kondisi sanitasi di lingkungan sekitar dan buat laporan komprehensif.',
    attachments: ['form-observasi.pdf', 'panduan-laporan.docx'],
    timeRemaining: '11 hari'
  },
  {
    id: 3,
    title: 'Studi Kasus Sertifikasi Halal',
    course: 'Sertifikasi Halal - Sistem Jaminan Halal',
    dueDate: '2024-01-20',
    submittedDate: '2024-01-18',
    status: 'submitted',
    priority: 'medium',
    points: 90,
    score: 85,
    description: 'Analisis proses sertifikasi halal pada produk makanan dan minuman.',
    attachments: ['studi-kasus.pdf'],
    timeRemaining: null
  },
  {
    id: 4,
    title: 'Presentasi Keamanan Pangan',
    course: 'Keamanan Pangan Industri',
    dueDate: '2024-01-28',
    submittedDate: null,
    status: 'overdue',
    priority: 'high',
    points: 100,
    description: 'Buat presentasi mengenai implementasi keamanan pangan di industri skala besar.',
    attachments: ['template-presentasi.pptx'],
    timeRemaining: 'Terlambat 2 hari'
  }
];

const statusConfig = {
  pending: {
    label: 'Belum Dikerjakan',
    color: 'bg-yellow-100 text-yellow-800',
    icon: ClockIcon
  },
  submitted: {
    label: 'Sudah Dikumpulkan',
    color: 'bg-green-100 text-green-800',
    icon: CheckCircleIcon
  },
  overdue: {
    label: 'Terlambat',
    color: 'bg-red-100 text-red-800',
    icon: ExclamationTriangleIcon
  }
};

const priorityConfig = {
  high: {
    label: 'Tinggi',
    color: 'border-l-red-500'
  },
  medium: {
    label: 'Sedang',
    color: 'border-l-yellow-500'
  },
  low: {
    label: 'Rendah',
    color: 'border-l-green-500'
  }
};

function formatDate(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleDateString('id-ID', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
}

export default function AssignmentsPage() {
  const [selectedAssignment, setSelectedAssignment] = useState<any>(null);
  const [showModal, setShowModal] = useState(false);
  const [modalType, setModalType] = useState<'detail' | 'work'>('detail');

  const handleWorkOnAssignment = (assignment: any) => {
    setSelectedAssignment(assignment);
    setModalType('work');
    setShowModal(true);
  };

  const handleViewDetail = (assignment: any) => {
    setSelectedAssignment(assignment);
    setModalType('detail');
    setShowModal(true);
  };

  const closeModal = () => {
    setShowModal(false);
    setSelectedAssignment(null);
  };

  const pendingAssignments = assignments.filter(a => a.status === 'pending');
  const submittedAssignments = assignments.filter(a => a.status === 'submitted');
  const overdueAssignments = assignments.filter(a => a.status === 'overdue');

  return (
    <DashboardLayout>
      <div className="p-6">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">Penugasan</h1>
          <p className="text-gray-600">Kelola dan kumpulkan tugas pembelajaran Anda</p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Total Tugas</p>
                <p className="text-2xl font-bold text-gray-900">{assignments.length}</p>
              </div>
              <div className="p-3 bg-blue-100 rounded-lg">
                <DocumentTextIcon className="h-6 w-6 text-blue-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Belum Dikerjakan</p>
                <p className="text-2xl font-bold text-yellow-600">{pendingAssignments.length}</p>
              </div>
              <div className="p-3 bg-yellow-100 rounded-lg">
                <ClockIcon className="h-6 w-6 text-yellow-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Sudah Dikumpulkan</p>
                <p className="text-2xl font-bold text-green-600">{submittedAssignments.length}</p>
              </div>
              <div className="p-3 bg-green-100 rounded-lg">
                <CheckCircleIcon className="h-6 w-6 text-green-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Terlambat</p>
                <p className="text-2xl font-bold text-red-600">{overdueAssignments.length}</p>
              </div>
              <div className="p-3 bg-red-100 rounded-lg">
                <ExclamationTriangleIcon className="h-6 w-6 text-red-600" />
              </div>
            </div>
          </div>
        </div>

        {/* Assignments List */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100">
          <div className="p-6 border-b border-gray-100">
            <h2 className="text-xl font-semibold text-gray-900">Daftar Tugas</h2>
          </div>
          <div className="p-6">
            <div className="space-y-6">
              {assignments.map((assignment) => {
                const StatusIcon = statusConfig[assignment.status as keyof typeof statusConfig].icon;
                
                return (
                  <div key={assignment.id} className={cn(
                    "border-l-4 pl-6 py-4 bg-gray-50 rounded-r-lg",
                    priorityConfig[assignment.priority as keyof typeof priorityConfig].color
                  )}>
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center mb-2">
                          <h3 className="font-semibold text-gray-900 mr-3">{assignment.title}</h3>
                          <span className={cn(
                            "px-2 py-1 rounded-full text-xs font-medium flex items-center",
                            statusConfig[assignment.status as keyof typeof statusConfig].color
                          )}>
                            <StatusIcon className="h-3 w-3 mr-1" />
                            {statusConfig[assignment.status as keyof typeof statusConfig].label}
                          </span>
                        </div>
                        
                        <p className="text-sm text-blue-600 mb-2 font-medium">{assignment.course}</p>
                        <p className="text-sm text-gray-600 mb-3">{assignment.description}</p>
                        
                        <div className="flex items-center text-sm text-gray-500 mb-3">
                          <CalendarIcon className="h-4 w-4 mr-1" />
                          <span className="mr-4">Deadline: {formatDate(assignment.dueDate)}</span>
                          {assignment.timeRemaining && (
                            <>
                              <ClockIcon className="h-4 w-4 mr-1" />
                              <span className={cn(
                                assignment.status === 'overdue' ? 'text-red-600 font-medium' : ''
                              )}>
                                {assignment.timeRemaining}
                              </span>
                            </>
                          )}
                        </div>
                        
                        {assignment.attachments && assignment.attachments.length > 0 && (
                          <div className="mb-3">
                            <p className="text-xs text-gray-500 mb-1">Lampiran:</p>
                            <div className="flex flex-wrap gap-2">
                              {assignment.attachments.map((file, index) => (
                                <span key={index} className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded">
                                  {file}
                                </span>
                              ))}
                            </div>
                          </div>
                        )}
                        
                        <div className="flex items-center justify-between">
                          <div className="flex items-center text-sm">
                            <span className="text-gray-600 mr-2">Poin:</span>
                            <span className="font-medium text-gray-900">{assignment.points}</span>
                            {assignment.score && (
                              <>
                                <span className="text-gray-400 mx-2">|</span>
                                <span className="text-gray-600 mr-2">Nilai:</span>
                                <span className="font-medium text-green-600">{assignment.score}</span>
                              </>
                            )}
                          </div>
                          
                          <div className="flex space-x-2">
                            {assignment.status === 'pending' && (
                              <>
                                <button 
                                  onClick={() => handleWorkOnAssignment(assignment)}
                                  className="px-4 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors"
                                >
                                  Kerjakan
                                </button>
                                <button 
                                  onClick={() => handleViewDetail(assignment)}
                                  className="px-4 py-2 bg-gray-100 text-gray-700 text-sm rounded-lg hover:bg-gray-200 transition-colors"
                                >
                                  Detail
                                </button>
                              </>
                            )}
                            {assignment.status === 'submitted' && (
                              <>
                                <button className="px-4 py-2 bg-green-100 text-green-700 text-sm rounded-lg hover:bg-green-200 transition-colors">
                                  Lihat Submission
                                </button>
                                <button 
                                  onClick={() => handleViewDetail(assignment)}
                                  className="px-4 py-2 bg-gray-100 text-gray-700 text-sm rounded-lg hover:bg-gray-200 transition-colors"
                                >
                                  Detail
                                </button>
                              </>
                            )}
                            {assignment.status === 'overdue' && (
                              <>
                                <button 
                                  onClick={() => handleWorkOnAssignment(assignment)}
                                  className="px-4 py-2 bg-red-600 text-white text-sm rounded-lg hover:bg-red-700 transition-colors"
                                >
                                  Kerjakan Sekarang
                                </button>
                                <button 
                                  onClick={() => handleViewDetail(assignment)}
                                  className="px-4 py-2 bg-gray-100 text-gray-700 text-sm rounded-lg hover:bg-gray-200 transition-colors"
                                >
                                  Detail
                                </button>
                              </>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* Modal */}
        {showModal && selectedAssignment && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white rounded-xl p-6 max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-xl font-semibold text-gray-900">
                  {modalType === 'detail' ? 'Detail Tugas' : 'Kerjakan Tugas'}
                </h3>
                <button 
                  onClick={closeModal}
                  className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <XMarkIcon className="h-5 w-5 text-gray-500" />
                </button>
              </div>
              
              <div className="space-y-4">
                <div>
                  <h4 className="font-semibold text-gray-900 mb-2">{selectedAssignment.title}</h4>
                  <p className="text-sm text-blue-600 mb-2">{selectedAssignment.course}</p>
                  <p className="text-gray-600">{selectedAssignment.description}</p>
                </div>
                
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-gray-500">Deadline:</span>
                    <p className="font-medium">{formatDate(selectedAssignment.dueDate)}</p>
                  </div>
                  <div>
                    <span className="text-gray-500">Poin:</span>
                    <p className="font-medium">{selectedAssignment.points}</p>
                  </div>
                </div>
                
                {selectedAssignment.attachments && selectedAssignment.attachments.length > 0 && (
                  <div>
                    <p className="text-sm text-gray-500 mb-2">Lampiran:</p>
                    <div className="space-y-2">
                      {selectedAssignment.attachments.map((file: string, index: number) => (
                        <div key={index} className="flex items-center justify-between p-2 bg-gray-50 rounded">
                          <span className="text-sm">{file}</span>
                          <button className="text-blue-600 text-sm hover:underline">Download</button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                
                {modalType === 'work' && (
                  <div className="border-t pt-4">
                    <h5 className="font-medium text-gray-900 mb-3">Submit Tugas</h5>
                    <div className="space-y-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                          Upload File
                        </label>
                        <input 
                          type="file" 
                          className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                          Catatan (Opsional)
                        </label>
                        <textarea 
                          rows={4}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                          placeholder="Tambahkan catatan untuk tugas ini..."
                        />
                      </div>
                      <div className="flex space-x-3">
                        <button className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center">
                          <PaperAirplaneIcon className="h-4 w-4 mr-2" />
                          Submit Tugas
                        </button>
                        <button 
                          onClick={closeModal}
                          className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
                        >
                          Batal
                        </button>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}