'use client';

import DashboardLayout from '@/layouts/DashboardLayout';
import { TrophyIcon, CalendarIcon, StarIcon, ArrowDownTrayIcon, EyeIcon, XMarkIcon } from '@heroicons/react/24/outline';
import { cn } from '@/utils/cn';
import { useState } from 'react';
import jsPDF from 'jspdf';

const certificates = [
  {
    id: 1,
    title: 'Sertifikat HACCP - Hazard Analysis Critical Control Point',
    course: 'HACCP - Hazard Analysis Critical Control Point',
    issuedDate: '2024-01-20',
    expiryDate: '2027-01-20',
    certificateNumber: 'HACCP-2024-001234',
    status: 'active',
    score: 88,
    grade: 'A',
    issuer: 'Lembaga Sertifikasi Keamanan Pangan Indonesia',
    credentialId: 'LSKPI-HACCP-2024-001234',
    skills: ['Hazard Analysis', 'Critical Control Points', 'Food Safety Management', 'Risk Assessment']
  },
  {
    id: 2,
    title: 'Sertifikat Sistem Jaminan Halal',
    course: 'Sertifikasi Halal - Sistem Jaminan Halal',
    issuedDate: '2024-01-18',
    expiryDate: '2026-01-18',
    certificateNumber: 'SJH-2024-005678',
    status: 'active',
    score: 92,
    grade: 'A+',
    issuer: 'Badan Penyelenggara Jaminan Produk Halal',
    credentialId: 'BPJPH-SJH-2024-005678',
    skills: ['Halal Certification', 'Islamic Law', 'Product Analysis', 'Halal Auditing']
  },
  {
    id: 3,
    title: 'Sertifikat Sanitasi Lingkungan Hidup Sehat',
    course: 'SLHS - Sanitasi Lingkungan Hidup Sehat',
    issuedDate: '2023-12-15',
    expiryDate: '2025-12-15',
    certificateNumber: 'SLHS-2023-009876',
    status: 'expiring_soon',
    score: 85,
    grade: 'A',
    issuer: 'Kementerian Kesehatan Republik Indonesia',
    credentialId: 'KEMKES-SLHS-2023-009876',
    skills: ['Environmental Sanitation', 'Public Health', 'Waste Management', 'Water Quality']
  },
  {
    id: 4,
    title: 'Sertifikat ISO 22000',
    course: 'Food Safety Management System',
    issuedDate: '2023-12-05',
    expiryDate: '2024-12-05',
    certificateNumber: 'ISO-2023-004',
    status: 'expired',
    score: 96,
    grade: 'A',
    issuer: 'LMS BGN Academy',
    credentialId: 'IS23-96234',
    skills: ['ISO Standards', 'Food Safety', 'Management System']
  }
];

const statusConfig = {
  active: {
    label: 'Aktif',
    color: 'bg-green-100 text-green-800 border-green-200',
    bgColor: 'bg-green-50'
  },
  expiring_soon: {
    label: 'Akan Berakhir',
    color: 'bg-yellow-100 text-yellow-800 border-yellow-200',
    bgColor: 'bg-yellow-50'
  },
  expired: {
    label: 'Kedaluwarsa',
    color: 'bg-red-100 text-red-800 border-red-200',
    bgColor: 'bg-red-50'
  }
};

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

function getGradeColor(grade: string) {
  switch (grade) {
    case 'A+':
      return 'text-green-600';
    case 'A':
      return 'text-blue-600';
    case 'B+':
      return 'text-yellow-600';
    case 'B':
      return 'text-orange-600';
    default:
      return 'text-gray-600';
  }
}

export default function CertificatesPage() {
  const [selectedCertificate, setSelectedCertificate] = useState<any>(null);
  const [showModal, setShowModal] = useState(false);

  const handleViewCertificate = (certificate: any) => {
    setSelectedCertificate(certificate);
    setShowModal(true);
  };

  const handleDownloadCertificate = (certificate: any) => {
    const doc = new jsPDF({
      orientation: 'landscape',
      unit: 'mm',
      format: 'a4'
    });

    // Set font
    doc.setFont('helvetica');
    
    // Background
    doc.setFillColor(248, 250, 252);
    doc.rect(0, 0, 297, 210, 'F');
    
    // Border
    doc.setDrawColor(59, 130, 246);
    doc.setLineWidth(2);
    doc.rect(10, 10, 277, 190);
    
    // Inner border
    doc.setDrawColor(147, 197, 253);
    doc.setLineWidth(1);
    doc.rect(15, 15, 267, 180);
    
    // Header
    doc.setFontSize(24);
    doc.setTextColor(30, 64, 175);
    doc.text('SERTIFIKAT KELULUSAN', 148.5, 40, { align: 'center' });
    
    doc.setFontSize(16);
    doc.setTextColor(75, 85, 99);
    doc.text('CERTIFICATE OF COMPLETION', 148.5, 50, { align: 'center' });
    
    // Certificate content
    doc.setFontSize(12);
    doc.setTextColor(55, 65, 81);
    doc.text('Dengan ini menyatakan bahwa:', 148.5, 70, { align: 'center' });
    
    doc.setFontSize(20);
    doc.setTextColor(17, 24, 39);
    doc.text('PESERTA KURSUS', 148.5, 85, { align: 'center' });
    
    doc.setFontSize(12);
    doc.setTextColor(55, 65, 81);
    doc.text('Telah berhasil menyelesaikan kursus:', 148.5, 100, { align: 'center' });
    
    doc.setFontSize(16);
    doc.setTextColor(30, 64, 175);
    const lines = doc.splitTextToSize(certificate.course, 200);
    doc.text(lines, 148.5, 115, { align: 'center' });
    
    // Details
    doc.setFontSize(10);
    doc.setTextColor(75, 85, 99);
    doc.text(`Nomor Sertifikat: ${certificate.certificateNumber}`, 30, 150);
    doc.text(`Tanggal Terbit: ${formatDate(certificate.issuedDate)}`, 30, 160);
    doc.text(`Berlaku Hingga: ${formatDate(certificate.expiryDate)}`, 30, 170);
    doc.text(`Nilai: ${certificate.score} (${certificate.grade})`, 200, 150);
    doc.text(`Credential ID: ${certificate.credentialId}`, 200, 160);
    doc.text(`Penerbit: ${certificate.issuer}`, 200, 170);
    
    // Footer
    doc.setFontSize(8);
    doc.setTextColor(107, 114, 128);
    doc.text('Sertifikat ini dapat diverifikasi melalui sistem LMS BGN Academy', 148.5, 185, { align: 'center' });
    
    // Save the PDF
    doc.save(`Sertifikat_${certificate.certificateNumber}.pdf`);
  };

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

  const activeCertificates = certificates.filter(c => c.status === 'active');
  const expiringSoonCertificates = certificates.filter(c => c.status === 'expiring_soon');

  return (
    <DashboardLayout>
      <div className="p-6">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">Sertifikat</h1>
          <p className="text-gray-600">Kelola dan unduh sertifikat 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 Sertifikat</p>
                <p className="text-2xl font-bold text-gray-900">{certificates.length}</p>
              </div>
              <div className="p-3 bg-blue-100 rounded-lg">
                <TrophyIcon 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">Aktif</p>
                <p className="text-2xl font-bold text-green-600">{activeCertificates.length}</p>
              </div>
              <div className="p-3 bg-green-100 rounded-lg">
                <TrophyIcon 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">Akan Berakhir</p>
                <p className="text-2xl font-bold text-yellow-600">{expiringSoonCertificates.length}</p>
              </div>
              <div className="p-3 bg-yellow-100 rounded-lg">
                <CalendarIcon 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">Rata-rata Nilai</p>
                <p className="text-2xl font-bold text-purple-600">88.3</p>
              </div>
              <div className="p-3 bg-purple-100 rounded-lg">
                <TrophyIcon className="h-6 w-6 text-purple-600" />
              </div>
            </div>
          </div>
        </div>

        {/* Certificates Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {certificates.map((certificate) => (
            <div key={certificate.id} className={cn(
              "bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden",
              statusConfig[certificate.status as keyof typeof statusConfig].bgColor
            )}>
              {/* Certificate Header */}
              <div className="bg-gradient-to-r from-blue-600 to-purple-600 p-6 text-white">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center mb-2">
                      <TrophyIcon className="h-6 w-6 mr-2" />
                      <span className={cn(
                        "px-3 py-1 rounded-full text-sm font-medium border",
                        statusConfig[certificate.status as keyof typeof statusConfig].color,
                        "bg-white"
                      )}>
                        {statusConfig[certificate.status as keyof typeof statusConfig].label}
                      </span>
                    </div>
                    <h3 className="text-lg font-semibold mb-2">{certificate.title}</h3>
                    <p className="text-blue-100 text-sm">{certificate.course}</p>
                  </div>
                  <div className="text-right">
                    <div className={cn(
                      "text-2xl font-bold",
                      getGradeColor(certificate.grade)
                    )}>
                      {certificate.grade}
                    </div>
                    <div className="text-blue-100 text-sm">{certificate.score}%</div>
                  </div>
                </div>
              </div>

              {/* Certificate Content */}
              <div className="p-6">
                {/* Certificate Details */}
                <div className="grid grid-cols-2 gap-4 mb-6">
                  <div>
                    <p className="text-sm text-gray-600 mb-1">Tanggal Terbit</p>
                    <p className="font-medium text-gray-900">{formatDate(certificate.issuedDate)}</p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-600 mb-1">Berlaku Hingga</p>
                    <p className="font-medium text-gray-900">{formatDate(certificate.expiryDate)}</p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-600 mb-1">Nomor Sertifikat</p>
                    <p className="font-medium text-gray-900 text-sm">{certificate.certificateNumber}</p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-600 mb-1">Credential ID</p>
                    <p className="font-medium text-gray-900 text-sm">{certificate.credentialId}</p>
                  </div>
                </div>

                {/* Issuer */}
                <div className="mb-6">
                  <p className="text-sm text-gray-600 mb-1">Penerbit</p>
                  <p className="font-medium text-gray-900">{certificate.issuer}</p>
                </div>

                {/* Skills */}
                <div className="mb-6">
                  <p className="text-sm text-gray-600 mb-3">Kompetensi yang Diperoleh</p>
                  <div className="flex flex-wrap gap-2">
                    {certificate.skills.map((skill, index) => (
                      <span key={index} className="px-3 py-1 bg-blue-100 text-blue-700 text-sm rounded-full">
                        {skill}
                      </span>
                    ))}
                  </div>
                </div>

                {/* Actions */}
                <div className="flex space-x-3">
                  <button 
                    onClick={() => handleViewCertificate(certificate)}
                    className="flex-1 flex items-center justify-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    <EyeIcon className="h-4 w-4 mr-2" />
                    Lihat
                  </button>
                  <button 
                    onClick={() => handleDownloadCertificate(certificate)}
                    className="flex-1 flex items-center justify-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
                  >
                    <ArrowDownTrayIcon className="h-4 w-4 mr-2" />
                    Unduh
                  </button>
                  <button className="flex items-center justify-center px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
                    <StarIcon className="h-4 w-4" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Empty State */}
        {certificates.length === 0 && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-12 text-center">
            <TrophyIcon className="h-16 w-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">Belum Ada Sertifikat</h3>
            <p className="text-gray-600 mb-6">Selesaikan kursus untuk mendapatkan sertifikat pertama Anda</p>
            <button className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
              Lihat Kursus
            </button>
          </div>
        )}

        {/* Certificate Modal */}
        {showModal && selectedCertificate && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <div className="bg-white rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
              {/* Modal Header */}
              <div className="flex items-center justify-between p-6 border-b border-gray-200">
                <h2 className="text-xl font-semibold text-gray-900">Detail Sertifikat</h2>
                <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>

              {/* Modal Content */}
              <div className="p-6">
                {/* Certificate Preview */}
                <div className="bg-gradient-to-br from-blue-600 to-purple-600 rounded-xl p-8 text-white mb-6">
                  <div className="text-center">
                    <TrophyIcon className="h-16 w-16 mx-auto mb-4 text-yellow-300" />
                    <h3 className="text-2xl font-bold mb-2">{selectedCertificate.title}</h3>
                    <p className="text-blue-100 mb-4">{selectedCertificate.course}</p>
                    <div className="flex items-center justify-center space-x-4">
                      <div className="text-center">
                        <div className="text-3xl font-bold text-yellow-300">{selectedCertificate.grade}</div>
                        <div className="text-sm text-blue-100">Grade</div>
                      </div>
                      <div className="text-center">
                        <div className="text-3xl font-bold text-yellow-300">{selectedCertificate.score}%</div>
                        <div className="text-sm text-blue-100">Score</div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Certificate Details */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                  <div>
                    <h4 className="font-semibold text-gray-900 mb-3">Informasi Sertifikat</h4>
                    <div className="space-y-3">
                      <div>
                        <p className="text-sm text-gray-600">Nomor Sertifikat</p>
                        <p className="font-medium text-gray-900">{selectedCertificate.certificateNumber}</p>
                      </div>
                      <div>
                        <p className="text-sm text-gray-600">Credential ID</p>
                        <p className="font-medium text-gray-900">{selectedCertificate.credentialId}</p>
                      </div>
                      <div>
                        <p className="text-sm text-gray-600">Penerbit</p>
                        <p className="font-medium text-gray-900">{selectedCertificate.issuer}</p>
                      </div>
                    </div>
                  </div>
                  <div>
                    <h4 className="font-semibold text-gray-900 mb-3">Tanggal</h4>
                    <div className="space-y-3">
                      <div>
                        <p className="text-sm text-gray-600">Tanggal Terbit</p>
                        <p className="font-medium text-gray-900">{formatDate(selectedCertificate.issuedDate)}</p>
                      </div>
                      <div>
                        <p className="text-sm text-gray-600">Berlaku Hingga</p>
                        <p className="font-medium text-gray-900">{formatDate(selectedCertificate.expiryDate)}</p>
                      </div>
                      <div>
                        <p className="text-sm text-gray-600">Status</p>
                        <span className={cn(
                          "px-3 py-1 rounded-full text-sm font-medium border",
                          statusConfig[selectedCertificate.status as keyof typeof statusConfig].color
                        )}>
                          {statusConfig[selectedCertificate.status as keyof typeof statusConfig].label}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Skills */}
                <div className="mb-6">
                  <h4 className="font-semibold text-gray-900 mb-3">Kompetensi yang Diperoleh</h4>
                  <div className="flex flex-wrap gap-2">
                    {selectedCertificate.skills.map((skill: string, index: number) => (
                      <span key={index} className="px-3 py-1 bg-blue-100 text-blue-700 text-sm rounded-full">
                        {skill}
                      </span>
                    ))}
                  </div>
                </div>

                {/* Modal Actions */}
                <div className="flex space-x-3">
                  <button 
                    onClick={() => handleDownloadCertificate(selectedCertificate)}
                    className="flex-1 flex items-center justify-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
                  >
                    <ArrowDownTrayIcon className="h-4 w-4 mr-2" />
                    Unduh Sertifikat
                  </button>
                  <button 
                    onClick={closeModal}
                    className="px-6 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
                  >
                    Tutup
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}