import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { MapPin, FileText, Video, Calendar, User, Users, Link } from 'lucide-react';

interface Metodology {
  id: number;
  name: string;
  description?: string;
}

interface EducationLevel {
  id: number;
  name: string;
  description?: string;
}

interface Category {
  id: number;
  name: string;
  description?: string;
}

interface ProjectImage {
  id: number;
  image_path: string;
}

interface User {
  id: number;
  name: string;
  email: string;
}

interface YouTubePreview {
  video_id: string | null;
  thumbnail: string | null;
  embed_url: string | null;
  is_valid: boolean;
}

interface Project {
  id: number;
  title: string;
  description?: string;
  creator: User;
  methodologies: Metodology[];
  education_levels: EducationLevel[];
  pdf_path?: string;
  video_url?: string;
  latitude?: string;
  longitude?: string;
  address?: string;
  categories: Category[];
  collaborators: User[];
  images: ProjectImage[];
  youtube_preview: YouTubePreview;
  guia_didactica?: string;
  informe_url?: string;
  otro_recurso?: string;
  created_at: string;
  updated_at: string;
}

interface ProjectModalProps {
  projectId: number;
  isOpen: boolean;
  onClose: () => void;
}

export default function ProjectModal({ projectId, isOpen, onClose }: ProjectModalProps) {
  const [project, setProject] = useState<Project | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchProject = async () => {
      setLoading(true);
      setError(null);

      try {
        const response = await fetch(`/api/projects/${projectId}/details`);
        if (!response.ok) {
          throw new Error('Failed to fetch project details');
        }
        const data = await response.json();
        setProject(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error');
        console.error('Error fetching project:', err);
      } finally {
        setLoading(false);
      }
    };

    if (isOpen && projectId) {
      fetchProject();
    }
  }, [isOpen, projectId]);

  if (loading) {
    return (
      <Dialog open={isOpen} onOpenChange={onClose}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-emerald-600"></div>
          </div>
        </DialogContent>
      </Dialog>
    );
  }

  if (error || !project) {
    return (
      <Dialog open={isOpen} onOpenChange={onClose}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="text-red-600">Error</DialogTitle>
          </DialogHeader>
          <div className="py-4">
            <p className="text-slate-600 dark:text-slate-300">
              {error || 'No se pudo cargar la información del proyecto.'}
            </p>
          </div>
          <Button onClick={onClose} className="w-full">
            Cerrar
          </Button>
        </DialogContent>
      </Dialog>
    );
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="text-2xl text-emerald-700 dark:text-emerald-400 pr-8">
            {project.title}
          </DialogTitle>
        </DialogHeader>

        {/* Video */}
        {project.video_url && project.youtube_preview.is_valid && project.youtube_preview.embed_url && (
          <div>
            <div className="flex items-center gap-2 mb-3">
              <Video className="w-4 h-4 text-emerald-600" />
              <h3 className="font-medium text-slate-900 dark:text-white">Video</h3>
            </div>
            <div className="aspect-video bg-slate-50 dark:bg-slate-800/50 rounded-lg overflow-hidden">
              <iframe
                src={project.youtube_preview.embed_url}
                title="YouTube video player"
                frameBorder="0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                allowFullScreen
                className="w-full h-full"
              />
            </div>
          </div>
        )}

        <div className="space-y-6">
          {/* Project Images */}
          {project.images.length > 0 && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {project.images.slice(0, 2).map((image) => (
                <div key={image.id} className="aspect-video">
                  <img
                    src={`/storage/${image.image_path}`}
                    alt="Imagen del proyecto"
                    className="w-full h-full object-cover rounded-lg border"
                  />
                </div>
              ))}
            </div>
          )}

          <div className='grid grid-cols-1 md:grid-cols-4 gap-6'>
            {/* PDF Document */}
            {project.pdf_path && (
              <div>
                <div className="flex items-center gap-2 mb-3">
                  <FileText className="w-4 h-4 text-emerald-600" />
                  <h3 className="font-medium text-slate-900 dark:text-white">Resumen</h3>
                </div>
                <a
                  href={`/storage/${project.pdf_path}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors"
                >
                  <FileText className="w-4 h-4" />
                  Ver Resumen
                </a>
              </div>
            )}

            {/* Guía Didáctica */}
            {project.guia_didactica && (
              <div>
                <div className="flex items-center gap-2 mb-3">
                  <FileText className="w-4 h-4 text-emerald-600" />
                  <h3 className="font-medium text-slate-900 dark:text-white">Guía Didáctica</h3>
                </div>
                <a
                  href={`/storage/${project.guia_didactica}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors"
                >
                  <FileText className="w-4 h-4" />
                  Ver Guía
                </a>
              </div>
            )}

            {/* Enlace al Repositorio */}
            {project.informe_url && (
              <div>
                <div className="flex items-center gap-2 mb-3">
                  <Link className="w-4 h-4 text-emerald-600" />
                  <h3 className="font-medium text-slate-900 dark:text-white">Enlace al Repositorio</h3>
                </div>
                <a
                  href={project.informe_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors"
                >
                  <Link className="w-4 h-4" />
                  Ver Repositorio
                </a>
              </div>
            )}

            {/* Otro Recurso */}
            {project.otro_recurso && (
              <div>
                <div className="flex items-center gap-2 mb-3">
                  <Link className="w-4 h-4 text-emerald-600" />
                  <h3 className="font-medium text-slate-900 dark:text-white">Otro Recurso</h3>
                </div>
                <a
                  href={project.otro_recurso}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors"
                >
                  <Link className="w-4 h-4" />
                  Ver Recurso
                </a>
              </div>
            )}
          </div>

          {/* Basic Information */}
          {/* <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <div className="flex items-center gap-2 mb-2">
                <User className="w-4 h-4 text-emerald-600" />
                <span className="font-medium text-slate-900 dark:text-white">Creador</span>
              </div>
              <div className="bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                <div className="font-medium">{project.creator.name}</div>
                <div className="text-sm text-slate-500">{project.creator.email}</div>
              </div>
            </div>

            <div>
              <div className="flex items-center gap-2 mb-2">
                <Calendar className="w-4 h-4 text-emerald-600" />
                <span className="font-medium text-slate-900 dark:text-white">Fecha de Registro</span>
              </div>
              <div className="bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                {new Date(project.created_at).toLocaleDateString('es-ES', {
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric'
                })}
              </div>
            </div>
          </div> */}

          {/* Categories */}
          {/* {project.categories.length > 0 && (
            <div>
              <h3 className="font-medium text-slate-900 dark:text-white mb-2">Categorías</h3>
              <div className="flex flex-wrap gap-2">
                {project.categories.map((category) => (
                  <Badge key={category.id} className="bg-emerald-100 text-emerald-800 dark:bg-emerald-900/20 dark:text-emerald-400">
                    {category.name}
                  </Badge>
                ))}
              </div>
            </div>
          )} */}

          {/* Collaborators */}
          {project.collaborators.length > 0 && (
            <div>
              <div className="flex items-center gap-2 mb-3">
                <Users className="w-4 h-4 text-emerald-600" />
                <h3 className="font-medium text-slate-900 dark:text-white">Investigadores</h3>
              </div>
              <div className="space-y-2">
                {project.collaborators.map((collaborator) => (
                  <div key={collaborator.id} className="flex items-center gap-3 p-3 bg-slate-50 dark:bg-slate-800/50 rounded-lg">
                    <div className="w-8 h-8 bg-emerald-100 dark:bg-emerald-900/20 rounded-full flex items-center justify-center">
                      <span className="text-emerald-600 dark:text-emerald-400 font-medium text-sm">
                        {collaborator.name.charAt(0).toUpperCase()}
                      </span>
                    </div>
                    <div>
                      <div className="font-medium text-slate-900 dark:text-white">
                        {collaborator.name}
                      </div>
                      <div className="text-sm text-slate-500 dark:text-slate-400">
                        {collaborator.email}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Location */}
          {/* {(project.latitude && project.longitude) && (
            <div>
              <div className="flex items-center gap-2 mb-3">
                <MapPin className="w-4 h-4 text-emerald-600" />
                <h3 className="font-medium text-slate-900 dark:text-white">Ubicación</h3>
              </div>
              {project.address && (
                <div className="bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg mb-3">
                  <p className="text-slate-700 dark:text-slate-300">{project.address}</p>
                </div>
              )}
              <div className="text-sm text-slate-600 dark:text-slate-400">
                Coordenadas: {project.latitude}, {project.longitude}
              </div>
            </div>
          )} */}


        </div>
      </DialogContent>
    </Dialog>
  );
}
