'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Plus, Film, Clock, ChevronRight, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Card, CardContent, CardHeader } from '@/components/ui/Card';
import { Input } from '@/components/ui/Input';
import type { Project } from '@/types/project';

export default function Home() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [newName, setNewName] = useState('');
  const [creating, setCreating] = useState(false);

  useEffect(() => {
    fetchProjects();
  }, []);

  const fetchProjects = async () => {
    try {
      const res = await fetch('/api/projects');
      const data = await res.json();
      setProjects(data);
    } catch (error) {
      console.error('Error fetching projects:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = async () => {
    if (!newName.trim()) return;
    setCreating(true);
    try {
      const res = await fetch('/api/projects', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: newName }),
      });
      if (res.ok) {
        setNewName('');
        setShowCreate(false);
        fetchProjects();
      }
    } catch (error) {
      console.error('Error creating project:', error);
    } finally {
      setCreating(false);
    }
  };

  const handleDelete = async (slug: string, e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (!confirm('¿Estás seguro de eliminar este proyecto?')) return;
    try {
      await fetch(`/api/projects/${slug}`, { method: 'DELETE' });
      fetchProjects();
    } catch (error) {
      console.error('Error deleting project:', error);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'bg-green-100 text-green-800';
      case 'in_progress': return 'bg-blue-100 text-blue-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getStepLabel = (step: string) => {
    switch (step) {
      case 'idea_motriz': return 'Idea Motriz';
      case 'personajes': return 'Personajes';
      case 'capitulos': return 'Capítulos';
      default: return step;
    }
  };

  return (
    <div className="min-h-screen bg-[var(--background)]">
      <header className="border-b border-stone-200/60 bg-white/80 backdrop-blur-sm sticky top-0 z-10">
        <div className="max-w-5xl mx-auto px-6 py-4 flex items-center justify-between">
          <div>
            <h1 className="text-lg font-semibold text-stone-900 tracking-tight">Story Studio</h1>
          </div>
          <Button size="sm" onClick={() => setShowCreate(true)}>
            <Plus className="w-3.5 h-3.5" />
            Nuevo proyecto
          </Button>
        </div>
      </header>

      {showCreate && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 animate-fade-in">
          <Card className="w-full max-w-md mx-4 shadow-xl shadow-black/10 animate-scale-in">
            <CardHeader>
              <h2 className="text-base font-semibold text-stone-900">Nuevo proyecto</h2>
              <p className="text-sm text-stone-500 mt-0.5">Dale un nombre a tu serie animada</p>
            </CardHeader>
            <CardContent className="space-y-4">
              <Input
                label="Nombre"
                value={newName}
                onChange={(e) => setNewName(e.target.value)}
                placeholder="Ej: Los Guardianes del Mundo Abierto"
                autoFocus
                onKeyDown={(e) => e.key === 'Enter' && handleCreate()}
              />
              <div className="flex gap-2 justify-end">
                <Button variant="ghost" size="sm" onClick={() => setShowCreate(false)}>
                  Cancelar
                </Button>
                <Button size="sm" onClick={handleCreate} loading={creating}>
                  Crear
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      <main className="max-w-5xl mx-auto px-6 py-10">
        {loading ? (
          <div className="flex items-center justify-center py-20">
            <div className="animate-spin w-5 h-5 border-2 border-indigo-600 border-t-transparent rounded-full" />
          </div>
        ) : projects.length === 0 ? (
          <div className="text-center py-24">
            <p className="text-stone-400 text-sm mb-6">Todavía no tienes proyectos</p>
            <Button onClick={() => setShowCreate(true)}>
              <Plus className="w-4 h-4" />
              Crear tu primer proyecto
            </Button>
          </div>
        ) : (
          <div className="space-y-1">
            <div className="px-3 pb-3">
              <span className="text-xs font-medium text-stone-400 uppercase tracking-wider">
                {projects.length} {projects.length === 1 ? 'proyecto' : 'proyectos'}
              </span>
            </div>
            {projects.map((project) => (
              <Link key={project.id} href={`/project/${project.slug}`} className="block group">
                <div className="flex items-center gap-4 px-4 py-3.5 rounded-lg hover:bg-white border border-transparent hover:border-stone-200/80 transition-all duration-150">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3">
                      <h3 className="font-medium text-stone-800 group-hover:text-stone-950 truncate transition-colors">
                        {project.name}
                      </h3>
                      <span className={`flex-shrink-0 px-2 py-0.5 text-[11px] font-medium rounded ${getStatusColor(project.status)}`}>
                        {project.status === 'completed' ? 'Completado' : project.status === 'in_progress' ? 'En progreso' : 'Borrador'}
                      </span>
                    </div>
                    <div className="flex items-center gap-3 mt-1">
                      <span className="text-xs text-stone-400">
                        {getStepLabel(project.currentStep)}
                      </span>
                      <span className="text-stone-300">&middot;</span>
                      <span className="text-xs text-stone-400">
                        {new Date(project.updatedAt).toLocaleDateString('es-ES', { day: 'numeric', month: 'short' })}
                      </span>
                    </div>
                  </div>
                  <button
                    onClick={(e) => handleDelete(project.slug, e)}
                    className="opacity-0 group-hover:opacity-100 p-1.5 text-stone-300 hover:text-red-500 hover:bg-red-50 rounded transition-all"
                    title="Eliminar proyecto"
                  >
                    <Trash2 className="w-3.5 h-3.5" />
                  </button>
                  <ChevronRight className="w-4 h-4 text-stone-300 group-hover:text-stone-400 transition-colors" />
                </div>
              </Link>
            ))}
          </div>
        )}
      </main>
    </div>
  );
}
