'use client';

import React from 'react';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { generateCertificatePDF, CertificatePDF, CertificateData } from '@/components/admin/CertificatePDF';

// Mock data for certificates
const mockCertificates: CertificateData[] = [
  {
    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',
    notes: 'Peserta menunjukkan kemampuan memasak dasar yang sangat baik.'
  },
  // Add more mock data as needed
];

export default function CertificateDetail({ params }: { params: { id: string } }) {
  const [certificate, setCertificate] = React.useState(mockCertificates.find(cert => cert.id === params.id));

  if (!certificate) {
    notFound();
  }

  const [showPreview, setShowPreview] = React.useState(false);
  const [isResending, setIsResending] = React.useState(false);
  const [isRevoking, setIsRevoking] = React.useState(false);

  const handleDownload = async () => {
    try {
      const result = await generateCertificatePDF(certificate);
      if (!result.success) {
        alert(result.error || 'Gagal mendownload PDF');
      }
    } catch (error) {
      console.error('Error downloading PDF:', error);
      alert('Terjadi kesalahan saat mendownload PDF');
    }
  };

  const handleResendEmail = async () => {
    if (!confirm('Apakah Anda yakin ingin mengirim ulang email sertifikat ini?')) {
      return;
    }

    setIsResending(true);
    try {
      const response = await fetch(`/api/certificates/${certificate.id}/resend`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      const result = await response.json();

      if (response.ok) {
        alert('Email sertifikat berhasil dikirim ulang!');
      } else {
        alert(`Gagal mengirim email: ${result.error || 'Terjadi kesalahan'}`);
      }
    } catch (error) {
      console.error('Error resending email:', error);
      alert('Terjadi kesalahan saat mengirim email');
    } finally {
      setIsResending(false);
    }
  };

  const handleRevoke = async () => {
    if (!confirm('Apakah Anda yakin ingin mencabut sertifikat ini? Tindakan ini tidak dapat dibatalkan.')) {
      return;
    }

    setIsRevoking(true);
    try {
      const response = await fetch(`/api/certificates/${certificate.id}/revoke`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      const result = await response.json();

      if (response.ok) {
        // Update local state
        setCertificate(prev => prev ? { ...prev, status: 'revoked' } : undefined);
        alert('Sertifikat berhasil dicabut!');
      } else {
        alert(`Gagal mencabut sertifikat: ${result.error || 'Terjadi kesalahan'}`);
      }
    } catch (error) {
      console.error('Error revoking certificate:', error);
      alert('Terjadi kesalahan saat mencabut sertifikat');
    } finally {
      setIsRevoking(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">Detail Sertifikat</h1>
        <Link href="/admin/certificates" className="text-blue-600 hover:text-blue-800">
          Kembali ke Daftar
        </Link>
      </div>

      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <h2 className="text-lg font-semibold mb-4">Informasi Penerima</h2>
            <dl className="space-y-2">
              <div>
                <dt className="text-sm font-medium text-gray-500">Nama</dt>
                <dd className="text-sm text-gray-900">{certificate.recipientName}</dd>
              </div>
              <div>
                <dt className="text-sm font-medium text-gray-500">Email</dt>
                <dd className="text-sm text-gray-900">{certificate.recipientEmail}</dd>
              </div>
            </dl>
          </div>

          <div>
            <h2 className="text-lg font-semibold mb-4">Informasi Sertifikat</h2>
            <dl className="space-y-2">
              <div>
                <dt className="text-sm font-medium text-gray-500">Nomor Sertifikat</dt>
                <dd className="text-sm text-gray-900">{certificate.certificateNumber}</dd>
              </div>
              <div>
                <dt className="text-sm font-medium text-gray-500">Kursus</dt>
                <dd className="text-sm text-gray-900">{certificate.courseName}</dd>
              </div>
              <div>
                <dt className="text-sm font-medium text-gray-500">Tanggal Selesai</dt>
                <dd className="text-sm text-gray-900">{certificate.completionDate}</dd>
              </div>
              <div>
                <dt className="text-sm font-medium text-gray-500">Nilai</dt>
                <dd className="text-sm text-gray-900">{certificate.score}</dd>
              </div>
              <div>
                <dt className="text-sm font-medium text-gray-500">Status</dt>
                <dd className="text-sm text-gray-900 capitalize">{certificate.status}</dd>
              </div>
              <div>
                <dt className="text-sm font-medium text-gray-500">Diterbitkan Oleh</dt>
                <dd className="text-sm text-gray-900">{certificate.issuedBy}</dd>
              </div>
            </dl>
          </div>
        </div>

        <div className="mt-6">
          <h2 className="text-lg font-semibold mb-4">Catatan Tambahan</h2>
          <p className="text-sm text-gray-600">{certificate.notes || 'Tidak ada catatan tambahan.'}</p>
        </div>

        <div className="mt-8 flex space-x-4">
          <button 
            onClick={handleDownload}
            className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700"
          >
            Download PDF
          </button>
          <button 
            onClick={handleResendEmail}
            className="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700"
          >
            Kirim Ulang Email
          </button>
          {certificate.status === 'issued' && (
            <button 
              onClick={handleRevoke}
              disabled={isRevoking}
              className="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isRevoking ? 'Memproses...' : 'Cabut Sertifikat'}
            </button>
          )}
          <button 
            onClick={() => setShowPreview(!showPreview)}
            className="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700"
          >
            {showPreview ? 'Sembunyikan Preview' : 'Preview PDF'}
          </button>
        </div>

        {showPreview && certificate && (
          <div className="mt-6 border border-gray-200 rounded-lg overflow-hidden">
            <CertificatePDF data={certificate} view={true} />
          </div>
        )}
      </div>
    </div>
  );
}