'use client';

import React, { useState } from 'react';
import Link from 'next/link';

interface Certificate {
  id: string;
  recipientName: string;
  recipientEmail: string;
  courseName: string;
  completionDate: string;
  certificateNumber: string;
  score: number;
  status: 'issued' | 'pending' | 'revoked';
  issuedBy: string;
  templateId: string;
}

const CertificatesPage: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [filterCourse, setFilterCourse] = useState('all');

  // Mock data
  const [certificates] = useState<Certificate[]>([
    {
      id: '1',
      recipientName: 'Andi Wijaya',
      recipientEmail: 'andi.wijaya@trainee.dapurmbg.com',
      courseName: 'Teknik Dasar Memasak',
      completionDate: '2024-01-15',
      certificateNumber: 'MBG-TDM-2024-001',
      score: 92,
      status: 'issued',
      issuedBy: 'Chef Ahmad Fauzi',
      templateId: 'template-1'
    },
    {
      id: '2',
      recipientName: 'Sari Dewi',
      recipientEmail: 'sari.dewi@trainee.dapurmbg.com',
      courseName: 'Food Safety & Hygiene',
      completionDate: '2024-01-14',
      certificateNumber: 'MBG-FSH-2024-002',
      score: 88,
      status: 'issued',
      issuedBy: 'Chef Rina Sari',
      templateId: 'template-2'
    },
    {
      id: '3',
      recipientName: 'Budi Santoso',
      recipientEmail: 'budi.santoso@trainee.dapurmbg.com',
      courseName: 'Kuliner Internasional',
      completionDate: '2024-01-13',
      certificateNumber: 'MBG-KI-2024-003',
      score: 85,
      status: 'pending',
      issuedBy: 'Chef Maria Gonzalez',
      templateId: 'template-3'
    },
    {
      id: '4',
      recipientName: 'Dewi Lestari',
      recipientEmail: 'dewi.lestari@trainee.dapurmbg.com',
      courseName: 'Pastry & Bakery',
      completionDate: '2024-01-12',
      certificateNumber: 'MBG-PB-2024-004',
      score: 90,
      status: 'issued',
      issuedBy: 'Chef Pierre Dubois',
      templateId: 'template-4'
    }
  ]);

  const courses = ['Teknik Dasar Memasak', 'Food Safety & Hygiene', 'Kuliner Internasional', 'Pastry & Bakery', 'Menu Planning & Costing'];

  const getStatusColor = (status: string) => {
    const colors = {
      issued: 'bg-green-100 text-green-800',
      pending: 'bg-yellow-100 text-yellow-800',
      revoked: 'bg-red-100 text-red-800'
    };
    return colors[status as keyof typeof colors] || 'bg-gray-100 text-gray-800';
  };

  const getStatusLabel = (status: string) => {
    const labels = {
      issued: 'Diterbitkan',
      pending: 'Menunggu',
      revoked: 'Dicabut'
    };
    return labels[status as keyof typeof labels] || status;
  };

  const getScoreColor = (score: number) => {
    if (score >= 90) return 'text-green-600';
    if (score >= 80) return 'text-blue-600';
    if (score >= 70) return 'text-yellow-600';
    return 'text-red-600';
  };

  const filteredCertificates = certificates.filter(certificate => {
    const matchesSearch = 
      certificate.recipientName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      certificate.certificateNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
      certificate.courseName.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = filterStatus === 'all' || certificate.status === filterStatus;
    const matchesCourse = filterCourse === 'all' || certificate.courseName === filterCourse;
    
    return matchesSearch && matchesStatus && matchesCourse;
  });

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Manajemen Sertifikat</h1>
          <p className="text-gray-600 mt-1">Kelola sertifikat peserta pelatihan Dapur MBG</p>
        </div>
        <div className="mt-4 sm:mt-0 flex items-center space-x-3">
          <Link
            href="/admin/certificates/templates"
            className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
          >
            Template Sertifikat
          </Link>
          <Link
            href="/admin/certificates/bulk-issue"
            className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
          >
            Terbitkan Massal
          </Link>
          <Link
            href="/admin/certificates/create"
            className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors inline-flex items-center"
          >
            <span className="mr-2">+</span>
            Terbitkan Sertifikat
          </Link>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-blue-600">{certificates.length}</div>
          <div className="text-sm text-gray-600">Total Sertifikat</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-green-600">
            {certificates.filter(c => c.status === 'issued').length}
          </div>
          <div className="text-sm text-gray-600">Diterbitkan</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-yellow-600">
            {certificates.filter(c => c.status === 'pending').length}
          </div>
          <div className="text-sm text-gray-600">Menunggu</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="text-2xl font-bold text-purple-600">
            {Math.round(certificates.reduce((acc, c) => acc + c.score, 0) / certificates.length)}
          </div>
          <div className="text-sm text-gray-600">Rata-rata Nilai</div>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {/* Search */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Cari Sertifikat
            </label>
            <input
              type="text"
              placeholder="Nama, nomor sertifikat, atau kursus..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          {/* Status Filter */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Status
            </label>
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="all">Semua Status</option>
              <option value="issued">Diterbitkan</option>
              <option value="pending">Menunggu</option>
              <option value="revoked">Dicabut</option>
            </select>
          </div>

          {/* Course Filter */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Kursus
            </label>
            <select
              value={filterCourse}
              onChange={(e) => setFilterCourse(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="all">Semua Kursus</option>
              {courses.map(course => (
                <option key={course} value={course}>{course}</option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Certificates List */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200">
        <div className="p-6 border-b border-gray-200">
          <h2 className="text-lg font-semibold text-gray-900">
            Daftar Sertifikat ({filteredCertificates.length})
          </h2>
        </div>
        
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Penerima
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Kursus
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Nomor Sertifikat
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Nilai
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Tanggal
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Aksi
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {filteredCertificates.map((certificate) => (
                <tr key={certificate.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4">
                    <div className="text-sm font-medium text-gray-900">
                      {certificate.recipientName}
                    </div>
                    <div className="text-xs text-gray-500">
                      {certificate.recipientEmail}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className="text-sm text-gray-900">{certificate.courseName}</span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className="text-sm font-mono text-gray-900">{certificate.certificateNumber}</span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`text-sm font-semibold ${getScoreColor(certificate.score)}`}>
                      {certificate.score}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getStatusColor(certificate.status)}`}>
                      {getStatusLabel(certificate.status)}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className="text-sm text-gray-900">{certificate.completionDate}</span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex space-x-2">
                      <Link
                        href={`/admin/certificates/${certificate.id}`}
                        className="text-blue-600 hover:text-blue-900"
                      >
                        Lihat
                      </Link>
                      <button className="text-green-600 hover:text-green-900">
                        Download
                      </button>
                      <button className="text-yellow-600 hover:text-yellow-900">
                        Kirim Ulang
                      </button>
                      {certificate.status === 'issued' && (
                        <button className="text-red-600 hover:text-red-900">
                          Cabut
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {filteredCertificates.length === 0 && (
          <div className="text-center py-12">
            <div className="text-gray-400 text-4xl mb-4">🏆</div>
            <h3 className="text-lg font-medium text-gray-900 mb-2">Tidak ada sertifikat ditemukan</h3>
            <p className="text-gray-600 mb-4">
              Coba ubah filter pencarian atau terbitkan sertifikat baru.
            </p>
            <Link
              href="/admin/certificates/create"
              className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors inline-flex items-center"
            >
              <span className="mr-2">+</span>
              Terbitkan Sertifikat Pertama
            </Link>
          </div>
        )}
      </div>
    </div>
  );
};

export default CertificatesPage;