/**
 * CertificateGenerator Component
 * Generate and download course completion certificates
 * Epic: OQI-002 Modulo Educativo
 */

import React, { useRef, useState, useCallback } from 'react';
import {
  AcademicCapIcon,
  ArrowDownTrayIcon,
  ShareIcon,
  PrinterIcon,
  CheckBadgeIcon,
  DocumentDuplicateIcon,
  XMarkIcon,
  ArrowPathIcon,
} from '@heroicons/react/24/solid';

// Types
export interface CertificateData {
  id: string;
  recipientName: string;
  courseName: string;
  courseInstructor: string;
  completionDate: Date;
  courseDuration: number;
  grade?: number;
  credentialId: string;
  issuerName: string;
  issuerLogo?: string;
  skills?: string[];
  signatureUrl?: string;
}

export interface CertificateTemplate {
  id: string;
  name: string;
  backgroundColor: string;
  accentColor: string;
  borderStyle: 'classic' | 'modern' | 'minimal';
  showBadge: boolean;
  showSkills: boolean;
}

interface CertificateGeneratorProps {
  certificate: CertificateData;
  template?: CertificateTemplate;
  onDownload?: (format: 'pdf' | 'png') => void;
  onShare?: (platform: 'linkedin' | 'twitter' | 'email' | 'copy') => void;
  onPrint?: () => void;
  isGenerating?: boolean;
  compact?: boolean;
}

const DEFAULT_TEMPLATE: CertificateTemplate = {
  id: 'default',
  name: 'Classic',
  backgroundColor: '#1f2937',
  accentColor: '#3b82f6',
  borderStyle: 'classic',
  showBadge: true,
  showSkills: true,
};

const TEMPLATES: CertificateTemplate[] = [
  DEFAULT_TEMPLATE,
  {
    id: 'modern',
    name: 'Modern',
    backgroundColor: '#111827',
    accentColor: '#10b981',
    borderStyle: 'modern',
    showBadge: true,
    showSkills: true,
  },
  {
    id: 'minimal',
    name: 'Minimal',
    backgroundColor: '#0f172a',
    accentColor: '#8b5cf6',
    borderStyle: 'minimal',
    showBadge: false,
    showSkills: false,
  },
];

const CertificateGenerator: React.FC<CertificateGeneratorProps> = ({
  certificate,
  template: initialTemplate = DEFAULT_TEMPLATE,
  onDownload,
  onShare,
  onPrint,
  isGenerating = false,
  compact = false,
}) => {
  const certificateRef = useRef<HTMLDivElement>(null);
  const [selectedTemplate, setSelectedTemplate] = useState<CertificateTemplate>(initialTemplate);
  const [showShareMenu, setShowShareMenu] = useState(false);
  const [copied, setCopied] = useState(false);

  // Format date
  const formatDate = (date: Date): string => {
    return date.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  // Format duration
  const formatDuration = (hours: number): string => {
    if (hours < 1) return `${Math.round(hours * 60)} minutes`;
    return `${hours} hour${hours !== 1 ? 's' : ''}`;
  };

  // Handle copy credential ID
  const handleCopyCredential = useCallback(() => {
    navigator.clipboard.writeText(certificate.credentialId);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }, [certificate.credentialId]);

  // Handle share
  const handleShare = useCallback(
    (platform: 'linkedin' | 'twitter' | 'email' | 'copy') => {
      onShare?.(platform);
      setShowShareMenu(false);
    },
    [onShare]
  );

  // Get border style classes
  const getBorderClasses = (style: CertificateTemplate['borderStyle']): string => {
    switch (style) {
      case 'classic':
        return 'border-4 border-double';
      case 'modern':
        return 'border-2 rounded-lg';
      case 'minimal':
        return 'border border-opacity-50';
      default:
        return 'border-2';
    }
  };

  return (
    <div className={`${compact ? 'space-y-4' : 'space-y-6'}`}>
      {/* Controls */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h2 className="text-xl font-bold text-white">Your Certificate</h2>
          <p className="text-gray-400 text-sm">
            Credential ID: {certificate.credentialId}
            <button
              onClick={handleCopyCredential}
              className="ml-2 text-blue-400 hover:text-blue-300"
              title="Copy"
            >
              {copied ? (
                <CheckBadgeIcon className="w-4 h-4 inline" />
              ) : (
                <DocumentDuplicateIcon className="w-4 h-4 inline" />
              )}
            </button>
          </p>
        </div>

        <div className="flex items-center gap-2">
          {/* Template Selector */}
          <select
            value={selectedTemplate.id}
            onChange={(e) => {
              const template = TEMPLATES.find((t) => t.id === e.target.value);
              if (template) setSelectedTemplate(template);
            }}
            className="bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
          >
            {TEMPLATES.map((t) => (
              <option key={t.id} value={t.id}>
                {t.name}
              </option>
            ))}
          </select>

          {/* Print Button */}
          {onPrint && (
            <button
              onClick={onPrint}
              className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
              title="Print"
            >
              <PrinterIcon className="w-5 h-5" />
            </button>
          )}

          {/* Share Button */}
          <div className="relative">
            <button
              onClick={() => setShowShareMenu(!showShareMenu)}
              className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
              title="Share"
            >
              <ShareIcon className="w-5 h-5" />
            </button>

            {showShareMenu && (
              <div className="absolute right-0 top-full mt-2 w-48 bg-gray-800 border border-gray-700 rounded-lg shadow-xl z-10">
                <div className="p-1">
                  <button
                    onClick={() => handleShare('linkedin')}
                    className="w-full flex items-center gap-2 px-3 py-2 text-sm text-white hover:bg-gray-700 rounded"
                  >
                    Share on LinkedIn
                  </button>
                  <button
                    onClick={() => handleShare('twitter')}
                    className="w-full flex items-center gap-2 px-3 py-2 text-sm text-white hover:bg-gray-700 rounded"
                  >
                    Share on Twitter
                  </button>
                  <button
                    onClick={() => handleShare('email')}
                    className="w-full flex items-center gap-2 px-3 py-2 text-sm text-white hover:bg-gray-700 rounded"
                  >
                    Send via Email
                  </button>
                  <button
                    onClick={() => handleShare('copy')}
                    className="w-full flex items-center gap-2 px-3 py-2 text-sm text-white hover:bg-gray-700 rounded"
                  >
                    Copy Link
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* Download Buttons */}
          {onDownload && (
            <div className="flex items-center gap-2">
              <button
                onClick={() => onDownload('pdf')}
                disabled={isGenerating}
                className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-500 disabled:opacity-50 transition-colors"
              >
                {isGenerating ? (
                  <ArrowPathIcon className="w-4 h-4 animate-spin" />
                ) : (
                  <ArrowDownTrayIcon className="w-4 h-4" />
                )}
                PDF
              </button>
              <button
                onClick={() => onDownload('png')}
                disabled={isGenerating}
                className="flex items-center gap-2 px-4 py-2 bg-gray-700 text-white rounded-lg hover:bg-gray-600 disabled:opacity-50 transition-colors"
              >
                PNG
              </button>
            </div>
          )}
        </div>
      </div>

      {/* Certificate Preview */}
      <div className="flex justify-center">
        <div
          ref={certificateRef}
          className={`relative w-full max-w-3xl aspect-[1.414/1] p-8 ${getBorderClasses(
            selectedTemplate.borderStyle
          )}`}
          style={{
            backgroundColor: selectedTemplate.backgroundColor,
            borderColor: selectedTemplate.accentColor,
          }}
        >
          {/* Decorative Elements */}
          {selectedTemplate.borderStyle === 'classic' && (
            <>
              <div
                className="absolute top-4 left-4 w-16 h-16 border-t-2 border-l-2"
                style={{ borderColor: selectedTemplate.accentColor }}
              />
              <div
                className="absolute top-4 right-4 w-16 h-16 border-t-2 border-r-2"
                style={{ borderColor: selectedTemplate.accentColor }}
              />
              <div
                className="absolute bottom-4 left-4 w-16 h-16 border-b-2 border-l-2"
                style={{ borderColor: selectedTemplate.accentColor }}
              />
              <div
                className="absolute bottom-4 right-4 w-16 h-16 border-b-2 border-r-2"
                style={{ borderColor: selectedTemplate.accentColor }}
              />
            </>
          )}

          {/* Content */}
          <div className="h-full flex flex-col justify-between text-center">
            {/* Header */}
            <div>
              {certificate.issuerLogo ? (
                <img
                  src={certificate.issuerLogo}
                  alt={certificate.issuerName}
                  className="h-12 mx-auto mb-4 object-contain"
                />
              ) : (
                <div className="flex items-center justify-center gap-2 mb-4">
                  <AcademicCapIcon className="w-10 h-10" style={{ color: selectedTemplate.accentColor }} />
                  <span className="text-xl font-bold text-white">{certificate.issuerName}</span>
                </div>
              )}

              <h1 className="text-3xl md:text-4xl font-serif text-white mb-2">
                Certificate of Completion
              </h1>
              <div
                className="w-32 h-1 mx-auto rounded"
                style={{ backgroundColor: selectedTemplate.accentColor }}
              />
            </div>

            {/* Body */}
            <div className="py-8">
              <p className="text-gray-400 text-lg mb-2">This is to certify that</p>
              <p
                className="text-3xl md:text-4xl font-semibold mb-4"
                style={{ color: selectedTemplate.accentColor }}
              >
                {certificate.recipientName}
              </p>
              <p className="text-gray-400 text-lg mb-2">has successfully completed the course</p>
              <p className="text-xl md:text-2xl font-medium text-white mb-4">
                {certificate.courseName}
              </p>

              {/* Details */}
              <div className="flex flex-wrap justify-center gap-6 text-sm text-gray-400 mt-6">
                <div>
                  <span className="block text-gray-500">Instructor</span>
                  <span className="text-white">{certificate.courseInstructor}</span>
                </div>
                <div>
                  <span className="block text-gray-500">Duration</span>
                  <span className="text-white">{formatDuration(certificate.courseDuration)}</span>
                </div>
                {certificate.grade && (
                  <div>
                    <span className="block text-gray-500">Grade</span>
                    <span className="text-white">{certificate.grade}%</span>
                  </div>
                )}
                <div>
                  <span className="block text-gray-500">Completed</span>
                  <span className="text-white">{formatDate(certificate.completionDate)}</span>
                </div>
              </div>

              {/* Skills */}
              {selectedTemplate.showSkills && certificate.skills && certificate.skills.length > 0 && (
                <div className="mt-6">
                  <p className="text-gray-500 text-sm mb-2">Skills Acquired</p>
                  <div className="flex flex-wrap justify-center gap-2">
                    {certificate.skills.map((skill) => (
                      <span
                        key={skill}
                        className="px-3 py-1 text-xs rounded-full"
                        style={{
                          backgroundColor: `${selectedTemplate.accentColor}20`,
                          color: selectedTemplate.accentColor,
                        }}
                      >
                        {skill}
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Footer */}
            <div className="flex items-end justify-between">
              {/* Signature */}
              <div className="text-left">
                {certificate.signatureUrl && (
                  <img
                    src={certificate.signatureUrl}
                    alt="Signature"
                    className="h-12 mb-1 object-contain"
                  />
                )}
                <div className="w-40 border-t border-gray-600 pt-1">
                  <p className="text-white text-sm">{certificate.courseInstructor}</p>
                  <p className="text-gray-500 text-xs">Instructor</p>
                </div>
              </div>

              {/* Badge */}
              {selectedTemplate.showBadge && (
                <div
                  className="flex flex-col items-center"
                  style={{ color: selectedTemplate.accentColor }}
                >
                  <CheckBadgeIcon className="w-16 h-16" />
                  <span className="text-xs text-gray-500 mt-1">Verified</span>
                </div>
              )}

              {/* Credential ID */}
              <div className="text-right">
                <p className="text-gray-500 text-xs mb-1">Credential ID</p>
                <p className="text-white text-sm font-mono">{certificate.credentialId}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Verification Info */}
      <div className="bg-gray-800/50 rounded-lg p-4 border border-gray-700">
        <div className="flex items-start gap-3">
          <CheckBadgeIcon className="w-6 h-6 text-green-400 flex-shrink-0" />
          <div>
            <h3 className="text-white font-medium">Certificate Verification</h3>
            <p className="text-gray-400 text-sm mt-1">
              This certificate can be verified using the credential ID above. Share the verification
              link with employers or add it to your LinkedIn profile.
            </p>
            <div className="flex items-center gap-2 mt-3">
              <input
                type="text"
                value={`https://platform.com/verify/${certificate.credentialId}`}
                readOnly
                className="flex-1 bg-gray-900/50 border border-gray-700 rounded px-3 py-1.5 text-sm text-gray-400"
              />
              <button
                onClick={handleCopyCredential}
                className="px-3 py-1.5 bg-gray-700 text-white text-sm rounded hover:bg-gray-600 transition-colors"
              >
                {copied ? 'Copied!' : 'Copy'}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CertificateGenerator;
