'use client';

import React from 'react';
import { Document, Page, Text, View, StyleSheet, PDFViewer, pdf } from '@react-pdf/renderer';

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

const styles = StyleSheet.create({
  page: {
    flexDirection: 'column',
    backgroundColor: '#ffffff',
    padding: 40,
    fontFamily: 'Helvetica',
  },
  header: {
    textAlign: 'center',
    marginBottom: 30,
  },
  title: {
    fontSize: 32,
    fontWeight: 'bold',
    color: '#1e40af',
    marginBottom: 10,
  },
  subtitle: {
    fontSize: 18,
    color: '#6b7280',
    marginBottom: 20,
  },
  certificateNumber: {
    fontSize: 14,
    color: '#6b7280',
    marginBottom: 30,
  },
  content: {
    marginBottom: 30,
  },
  recipientName: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#1f2937',
    textAlign: 'center',
    marginBottom: 20,
  },
  courseName: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#1e40af',
    textAlign: 'center',
    marginBottom: 15,
  },
  completionText: {
    fontSize: 14,
    color: '#4b5563',
    textAlign: 'center',
    marginBottom: 10,
  },
  score: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#059669',
    textAlign: 'center',
    marginBottom: 20,
  },
  footer: {
    marginTop: 40,
    borderTopWidth: 1,
    borderTopColor: '#e5e7eb',
    paddingTop: 20,
  },
  issuedBy: {
    fontSize: 14,
    color: '#6b7280',
    textAlign: 'center',
    marginBottom: 10,
  },
  completionDate: {
    fontSize: 14,
    color: '#6b7280',
    textAlign: 'center',
  },
  logo: {
    width: 80,
    height: 80,
    marginBottom: 20,
    alignSelf: 'center',
  },
  seal: {
    width: 60,
    height: 60,
    alignSelf: 'center',
    marginTop: 20,
  },
});

const CertificateDocument: React.FC<{ data: CertificateData }> = ({ data }) => (
  <Document>
    <Page size="A4" style={styles.page}>
      <View style={styles.header}>
        <Text style={styles.title}>SERTIFIKAT PENYELESAIAN</Text>
        <Text style={styles.subtitle}>Certificate of Completion</Text>
        <Text style={styles.certificateNumber}>No. {data.certificateNumber}</Text>
      </View>

      <View style={styles.content}>
        <Text style={styles.completionText}>
          Diberikan kepada / This is to certify that
        </Text>
        <Text style={styles.recipientName}>{data.recipientName}</Text>
        <Text style={styles.completionText}>
          Telah berhasil menyelesaikan kursus / Has successfully completed the course
        </Text>
        <Text style={styles.courseName}>{data.courseName}</Text>
        <Text style={styles.score}>Dengan nilai / With score: {data.score}/100</Text>
      </View>

      <View style={styles.footer}>
        <Text style={styles.issuedBy}>
          Diterbitkan oleh / Issued by: {data.issuedBy}
        </Text>
        <Text style={styles.completionDate}>
          Tanggal / Date: {data.completionDate}
        </Text>
      </View>
    </Page>
  </Document>
);

export const CertificatePDF: React.FC<{ data: CertificateData; view?: boolean }> = ({ data, view = false }) => {
  if (view) {
    return (
      <PDFViewer width="100%" height="600px">
        <CertificateDocument data={data} />
      </PDFViewer>
    );
  }
  return <CertificateDocument data={data} />;
};

export const generateCertificatePDF = async (data: CertificateData) => {
  try {
    const blob = await pdf(<CertificateDocument data={data} />).toBlob();
    const url = URL.createObjectURL(blob);
    
    // Create download link
    const link = document.createElement('a');
    link.href = url;
    link.download = `sertifikat-${data.certificateNumber.replace(/[^a-zA-Z0-9]/g, '-')}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // Cleanup
    setTimeout(() => URL.revokeObjectURL(url), 100);
    
    return { success: true };
  } catch (error) {
    console.error('Error generating PDF:', error);
    return { success: false, error: 'Gagal membuat PDF' };
  }
};

export default CertificatePDF;