/**
 * EarnedCertificates Component
 * Displays all earned certificates for user profile
 * OQI-002: Modulo Educativo - SUBTASK-007
 */

import React, { useState, useMemo } from 'react';
import {
  Award,
  Download,
  Share2,
  ExternalLink,
  Calendar,
  Clock,
  BadgeCheck,
  Search,
  Grid,
  List,
  Trophy,
  Loader2,
} from 'lucide-react';

export interface EarnedCertificate {
  id: string;
  credentialId: string;
  courseId: string;
  courseTitle: string;
  courseThumbnail?: string;
  instructorName: string;
  completedAt: string;
  issuedAt: string;
  grade?: number;
  xpEarned: number;
  courseDurationHours: number;
  skills?: string[];
  verificationUrl?: string;
  downloadUrl?: string;
}

interface EarnedCertificatesProps {
  certificates: EarnedCertificate[];
  loading?: boolean;
  onDownload?: (certificateId: string) => void;
  onShare?: (certificateId: string, platform: 'linkedin' | 'twitter' | 'email' | 'copy') => void;
  onViewCertificate?: (certificateId: string) => void;
  compact?: boolean;
}

type ViewMode = 'grid' | 'list';
type SortBy = 'newest' | 'oldest' | 'grade' | 'course';

const EarnedCertificates: React.FC<EarnedCertificatesProps> = ({
  certificates,
  loading = false,
  onDownload,
  onShare,
  onViewCertificate,
  compact = false,
}) => {
  const [viewMode, setViewMode] = useState<ViewMode>('grid');
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<SortBy>('newest');
  const [showShareMenu, setShowShareMenu] = useState<string | null>(null);

  // Filter and sort certificates
  const filteredCertificates = useMemo(() => {
    let result = [...certificates];

    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      result = result.filter(
        (cert) =>
          cert.courseTitle.toLowerCase().includes(query) ||
          cert.instructorName.toLowerCase().includes(query) ||
          cert.skills?.some((skill) => skill.toLowerCase().includes(query))
      );
    }

    // Sort
    switch (sortBy) {
      case 'oldest':
        result.sort((a, b) => new Date(a.issuedAt).getTime() - new Date(b.issuedAt).getTime());
        break;
      case 'grade':
        result.sort((a, b) => (b.grade || 0) - (a.grade || 0));
        break;
      case 'course':
        result.sort((a, b) => a.courseTitle.localeCompare(b.courseTitle));
        break;
      case 'newest':
      default:
        result.sort((a, b) => new Date(b.issuedAt).getTime() - new Date(a.issuedAt).getTime());
    }

    return result;
  }, [certificates, searchQuery, sortBy]);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('es-ES', {
      day: 'numeric',
      month: 'long',
      year: 'numeric',
    });
  };

  const handleShare = (certId: string, platform: 'linkedin' | 'twitter' | 'email' | 'copy') => {
    onShare?.(certId, platform);
    setShowShareMenu(null);
  };

  // Loading state
  if (loading) {
    return (
      <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-yellow-400 animate-spin" />
        </div>
      </div>
    );
  }

  // Empty state
  if (certificates.length === 0) {
    return (
      <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
        <div className="flex items-center gap-3 mb-4">
          <div className="p-2 bg-yellow-500/20 rounded-lg">
            <Award className="w-5 h-5 text-yellow-400" />
          </div>
          <h3 className="font-semibold text-white">Mis Certificados</h3>
        </div>
        <div className="text-center py-8">
          <Trophy className="w-16 h-16 text-gray-600 mx-auto mb-4" />
          <p className="text-gray-400">Aun no has obtenido ningun certificado</p>
          <p className="text-sm text-gray-500 mt-1">
            Completa cursos para obtener certificados
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-yellow-500/20 rounded-lg">
            <Award className="w-5 h-5 text-yellow-400" />
          </div>
          <div>
            <h3 className="font-semibold text-white">Mis Certificados</h3>
            <p className="text-xs text-gray-500">{certificates.length} certificados obtenidos</p>
          </div>
        </div>

        {/* View Toggle */}
        <div className="flex items-center gap-1 bg-gray-700 rounded-lg p-1">
          <button
            onClick={() => setViewMode('grid')}
            className={`p-1.5 rounded ${
              viewMode === 'grid' ? 'bg-gray-600 text-white' : 'text-gray-400 hover:text-white'
            }`}
          >
            <Grid className="w-4 h-4" />
          </button>
          <button
            onClick={() => setViewMode('list')}
            className={`p-1.5 rounded ${
              viewMode === 'list' ? 'bg-gray-600 text-white' : 'text-gray-400 hover:text-white'
            }`}
          >
            <List className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Search and Sort */}
      <div className="flex items-center gap-3 mb-4">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
          <input
            type="text"
            placeholder="Buscar certificados..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-9 pr-4 py-2 bg-gray-900/50 border border-gray-700 rounded-lg text-sm text-white placeholder-gray-500 focus:border-yellow-500/50 focus:outline-none"
          />
        </div>
        <select
          value={sortBy}
          onChange={(e) => setSortBy(e.target.value as SortBy)}
          className="px-3 py-2 bg-gray-900/50 border border-gray-700 rounded-lg text-sm text-white focus:border-yellow-500/50 focus:outline-none"
        >
          <option value="newest">Mas recientes</option>
          <option value="oldest">Mas antiguos</option>
          <option value="grade">Por calificacion</option>
          <option value="course">Por curso</option>
        </select>
      </div>

      {/* Certificates Display */}
      {filteredCertificates.length === 0 ? (
        <div className="text-center py-8">
          <p className="text-gray-400">No se encontraron certificados</p>
        </div>
      ) : viewMode === 'grid' ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredCertificates.map((cert) => (
            <div
              key={cert.id}
              className="bg-gradient-to-br from-gray-800 to-gray-900 rounded-xl border border-yellow-500/20 overflow-hidden hover:border-yellow-500/40 transition-colors group"
            >
              {/* Certificate Preview */}
              <div
                className="relative aspect-[1.4/1] bg-gradient-to-r from-yellow-600/10 via-amber-500/10 to-yellow-600/10 p-4 cursor-pointer"
                onClick={() => onViewCertificate?.(cert.id)}
              >
                <div className="absolute inset-0 flex flex-col items-center justify-center text-center p-4">
                  <Award className="w-10 h-10 text-yellow-400 mb-2" />
                  <p className="text-xs text-yellow-400/70 mb-1">Certificado de Finalizacion</p>
                  <p className="text-sm font-medium text-white line-clamp-2">{cert.courseTitle}</p>
                </div>
                <div className="absolute top-2 right-2">
                  <BadgeCheck className="w-6 h-6 text-yellow-400" />
                </div>
              </div>

              {/* Certificate Info */}
              <div className="p-3">
                <div className="flex items-center justify-between mb-2">
                  <span className="text-xs text-gray-400 flex items-center gap-1">
                    <Calendar className="w-3 h-3" />
                    {formatDate(cert.issuedAt)}
                  </span>
                  {cert.grade && (
                    <span className="text-xs text-green-400 font-medium">{cert.grade}%</span>
                  )}
                </div>

                <p className="text-sm text-gray-400 mb-3">{cert.instructorName}</p>

                {/* Skills Tags */}
                {cert.skills && cert.skills.length > 0 && (
                  <div className="flex flex-wrap gap-1 mb-3">
                    {cert.skills.slice(0, 3).map((skill) => (
                      <span
                        key={skill}
                        className="px-2 py-0.5 bg-yellow-500/10 text-yellow-400 text-xs rounded"
                      >
                        {skill}
                      </span>
                    ))}
                    {cert.skills.length > 3 && (
                      <span className="text-xs text-gray-500">+{cert.skills.length - 3}</span>
                    )}
                  </div>
                )}

                {/* Actions */}
                <div className="flex items-center gap-2">
                  {onDownload && (
                    <button
                      onClick={() => onDownload(cert.id)}
                      className="flex-1 flex items-center justify-center gap-1 py-1.5 bg-gray-700 hover:bg-gray-600 text-white text-xs rounded transition-colors"
                    >
                      <Download className="w-3 h-3" />
                      PDF
                    </button>
                  )}
                  {onShare && (
                    <div className="relative">
                      <button
                        onClick={() =>
                          setShowShareMenu(showShareMenu === cert.id ? null : cert.id)
                        }
                        className="p-1.5 bg-gray-700 hover:bg-gray-600 text-white rounded transition-colors"
                      >
                        <Share2 className="w-3 h-3" />
                      </button>
                      {showShareMenu === cert.id && (
                        <div className="absolute bottom-full right-0 mb-2 w-36 bg-gray-800 border border-gray-700 rounded-lg shadow-xl z-10">
                          <div className="p-1">
                            <button
                              onClick={() => handleShare(cert.id, 'linkedin')}
                              className="w-full px-3 py-1.5 text-xs text-left text-white hover:bg-gray-700 rounded"
                            >
                              LinkedIn
                            </button>
                            <button
                              onClick={() => handleShare(cert.id, 'twitter')}
                              className="w-full px-3 py-1.5 text-xs text-left text-white hover:bg-gray-700 rounded"
                            >
                              Twitter
                            </button>
                            <button
                              onClick={() => handleShare(cert.id, 'copy')}
                              className="w-full px-3 py-1.5 text-xs text-left text-white hover:bg-gray-700 rounded"
                            >
                              Copiar enlace
                            </button>
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                  {cert.verificationUrl && (
                    <a
                      href={cert.verificationUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="p-1.5 bg-gray-700 hover:bg-gray-600 text-white rounded transition-colors"
                    >
                      <ExternalLink className="w-3 h-3" />
                    </a>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="space-y-2">
          {filteredCertificates.map((cert) => (
            <div
              key={cert.id}
              className="flex items-center gap-4 p-4 bg-gray-900/50 rounded-lg border border-gray-700 hover:border-yellow-500/30 transition-colors"
            >
              {/* Icon */}
              <div className="p-3 bg-yellow-500/20 rounded-lg flex-shrink-0">
                <Award className="w-6 h-6 text-yellow-400" />
              </div>

              {/* Info */}
              <div className="flex-1 min-w-0">
                <h4
                  className="font-medium text-white truncate cursor-pointer hover:text-yellow-400 transition-colors"
                  onClick={() => onViewCertificate?.(cert.id)}
                >
                  {cert.courseTitle}
                </h4>
                <div className="flex items-center gap-3 text-xs text-gray-400 mt-1">
                  <span>{cert.instructorName}</span>
                  <span className="flex items-center gap-1">
                    <Calendar className="w-3 h-3" />
                    {formatDate(cert.issuedAt)}
                  </span>
                  <span className="flex items-center gap-1">
                    <Clock className="w-3 h-3" />
                    {cert.courseDurationHours}h
                  </span>
                </div>
                {cert.skills && cert.skills.length > 0 && (
                  <div className="flex flex-wrap gap-1 mt-2">
                    {cert.skills.slice(0, 4).map((skill) => (
                      <span
                        key={skill}
                        className="px-2 py-0.5 bg-yellow-500/10 text-yellow-400 text-xs rounded"
                      >
                        {skill}
                      </span>
                    ))}
                  </div>
                )}
              </div>

              {/* Grade */}
              {cert.grade && (
                <div className="text-right flex-shrink-0">
                  <div className="text-xl font-bold text-green-400">{cert.grade}%</div>
                  <div className="text-xs text-gray-500">Calificacion</div>
                </div>
              )}

              {/* Actions */}
              <div className="flex items-center gap-2 flex-shrink-0">
                {onDownload && (
                  <button
                    onClick={() => onDownload(cert.id)}
                    className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
                    title="Descargar PDF"
                  >
                    <Download className="w-4 h-4" />
                  </button>
                )}
                {onShare && (
                  <button
                    onClick={() => handleShare(cert.id, 'copy')}
                    className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
                    title="Compartir"
                  >
                    <Share2 className="w-4 h-4" />
                  </button>
                )}
                {cert.verificationUrl && (
                  <a
                    href={cert.verificationUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
                    title="Verificar"
                  >
                    <ExternalLink className="w-4 h-4" />
                  </a>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Credential ID Info */}
      <div className="mt-4 p-3 bg-gray-900/50 rounded-lg border border-gray-700">
        <div className="flex items-center gap-2 text-xs text-gray-400">
          <BadgeCheck className="w-4 h-4 text-green-400" />
          <span>
            Todos los certificados incluyen un ID unico de verificacion para validar su autenticidad
          </span>
        </div>
      </div>
    </div>
  );
};

export default EarnedCertificates;
