'use client';

import React, { useState, use } from 'react';
import Link from 'next/link';
import { INITIAL_OBRAS, INITIAL_FOTOS } from '@/lib/data/mockData';
import { FotoAvance } from '@/types';
import { 
  Image as ImageIcon, Plus, Search, Filter, ArrowLeft, 
  Upload, Tag, Calendar, User, X
} from 'lucide-react';

interface PageProps {
  params: Promise<{ obraId: string }>;
}

export default function FotosObraPage({ params }: PageProps) {
  const resolvedParams = use(params);
  const obraId = resolvedParams.obraId;

  const obra = INITIAL_OBRAS.find(o => o.id === obraId) || INITIAL_OBRAS[0];

  const [fotos, setFotos] = useState<FotoAvance[]>(
    INITIAL_FOTOS.filter(f => f.obraId === obraId)
  );

  const [filtroEtiqueta, setFiltroEtiqueta] = useState<string>('todas');
  const [fotoLightbox, setFotoLightbox] = useState<FotoAvance | null>(null);
  const [modalSubirFoto, setModalSubirFoto] = useState(false);

  // Form Subir Foto
  const [titulo, setTitulo] = useState('');
  const [descripcion, setDescripcion] = useState('');
  const [etiqueta, setEtiqueta] = useState<FotoAvance['etiqueta']>('Obra Gruesa');
  const [imageUrl, setImageUrl] = useState('https://images.unsplash.com/photo-1541888946425-d0fbb186a5b3?auto=format&fit=crop&w=800&q=80');

  const fotosFiltradas = fotos.filter(f => 
    filtroEtiqueta === 'todas' || f.etiqueta === filtroEtiqueta
  );

  const handleSubirFoto = (e: React.FormEvent) => {
    e.preventDefault();
    const nuevaFoto: FotoAvance = {
      id: `foto-${Date.now()}`,
      obraId,
      titulo,
      descripcion,
      imageUrl,
      fecha: new Date().toISOString().split('T')[0],
      etiqueta,
      autorNombre: 'Marcos Silva (Jefe de Terreno)'
    };

    setFotos([nuevaFoto, ...fotos]);
    setModalSubirFoto(false);
    setTitulo('');
    setDescripcion('');
  };

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 flex flex-col justify-between selection:bg-purple-500 selection:text-white">
      {/* Header Bar */}
      <header className="border-b border-slate-800 bg-slate-900 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <Link href={`/obra/${obraId}/dashboard`} className="p-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-lg">
              <ArrowLeft className="w-4 h-4" />
            </Link>
            <div>
              <h1 className="font-bold text-white text-base">Galería de Avances Fotográficos</h1>
              <span className="text-xs text-slate-400 block">{obra.nombre} — Bitácora de Terreno</span>
            </div>
          </div>

          <button
            onClick={() => setModalSubirFoto(true)}
            className="bg-purple-600 hover:bg-purple-500 text-white text-xs px-3.5 py-2 rounded-xl font-bold flex items-center space-x-1.5 shadow-md transition-all"
          >
            <Upload className="w-4 h-4" />
            <span>Subir Fotos de Terreno</span>
          </button>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 flex-1 w-full space-y-6">
        {/* Filtro por Etiqueta */}
        <div className="flex items-center space-x-2 bg-slate-900/60 p-4 rounded-2xl border border-slate-800 text-xs overflow-x-auto">
          <span className="text-slate-400 font-medium">Etapa / Sector:</span>
          {['todas', 'Obra Gruesa', 'Instalaciones', 'Terminaciones', 'Fachada'].map((t) => (
            <button
              key={t}
              onClick={() => setFiltroEtiqueta(t)}
              className={`px-3 py-1.5 rounded-lg capitalize font-medium transition-all ${
                filtroEtiqueta === t ? 'bg-purple-600 text-white font-bold' : 'text-slate-400 hover:text-white hover:bg-slate-800'
              }`}
            >
              {t}
            </button>
          ))}
        </div>

        {/* Grid de Fotografías */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {fotosFiltradas.map((foto) => (
            <div
              key={foto.id}
              onClick={() => setFotoLightbox(foto)}
              className="glass-card rounded-2xl overflow-hidden border border-slate-800 cursor-pointer group flex flex-col justify-between"
            >
              <div>
                <div className="relative h-52 w-full bg-slate-900 overflow-hidden">
                  <img
                    src={foto.imageUrl}
                    alt={foto.titulo}
                    className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-950/20 to-transparent" />

                  <span className="absolute top-3 right-3 px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-purple-950/90 text-purple-300 border border-purple-700/60">
                    {foto.etiqueta}
                  </span>
                </div>

                <div className="p-4">
                  <h3 className="text-base font-bold text-white group-hover:text-purple-400 transition-colors mb-1">
                    {foto.titulo}
                  </h3>
                  <p className="text-slate-300 text-xs line-clamp-2 mb-3">{foto.descripcion}</p>
                </div>
              </div>

              <div className="px-4 pb-4 pt-0 flex items-center justify-between text-[11px] text-slate-400 border-t border-slate-800/80 pt-3">
                <span className="flex items-center space-x-1">
                  <User className="w-3 h-3 text-purple-400" />
                  <span>{foto.autorNombre}</span>
                </span>
                <span className="flex items-center space-x-1 font-mono">
                  <Calendar className="w-3 h-3 text-slate-500" />
                  <span>{foto.fecha}</span>
                </span>
              </div>
            </div>
          ))}
        </div>
      </main>

      {/* Lightbox Modal */}
      {fotoLightbox && (
        <div className="fixed inset-0 bg-slate-950/90 backdrop-blur-md z-50 flex items-center justify-center p-4">
          <div className="glass-panel max-w-3xl w-full rounded-2xl overflow-hidden border border-slate-800 relative">
            <button
              onClick={() => setFotoLightbox(null)}
              className="absolute top-4 right-4 p-2 bg-slate-900/80 hover:bg-slate-800 text-white rounded-full z-10"
            >
              <X className="w-5 h-5" />
            </button>

            <div className="max-h-[65vh] w-full bg-slate-950 flex items-center justify-center overflow-hidden">
              <img src={fotoLightbox.imageUrl} alt={fotoLightbox.titulo} className="max-h-[65vh] w-full object-contain" />
            </div>

            <div className="p-6 bg-slate-900">
              <div className="flex justify-between items-start mb-2">
                <div>
                  <span className="text-xs font-bold text-purple-400 uppercase tracking-wider">{fotoLightbox.etiqueta} • {fotoLightbox.fecha}</span>
                  <h3 className="text-lg font-bold text-white">{fotoLightbox.titulo}</h3>
                </div>
                <span className="text-xs text-slate-400">Capturado por: {fotoLightbox.autorNombre}</span>
              </div>
              <p className="text-slate-300 text-xs">{fotoLightbox.descripcion}</p>
            </div>
          </div>
        </div>
      )}

      {/* Modal Subir Foto */}
      {modalSubirFoto && (
        <div className="fixed inset-0 bg-slate-950/80 backdrop-blur-md z-50 flex items-center justify-center p-4">
          <div className="glass-panel max-w-md w-full p-6 rounded-2xl border border-slate-800 shadow-2xl">
            <h3 className="text-lg font-bold text-white mb-1">Subir Foto de Avance de Terreno</h3>
            <p className="text-slate-400 text-xs mb-4">Registra el progreso visual de la obra.</p>

            <form onSubmit={handleSubirFoto} className="space-y-3 text-xs">
              <div>
                <label className="block text-slate-300 mb-1">Título de la Fotografía</label>
                <input
                  type="text"
                  required
                  placeholder="ej. Armadura de Losa Nivel 5"
                  value={titulo}
                  onChange={(e) => setTitulo(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-800 rounded-xl text-white"
                />
              </div>

              <div>
                <label className="block text-slate-300 mb-1">Etiqueta de Etapa</label>
                <select
                  value={etiqueta}
                  onChange={(e) => setEtiqueta(e.target.value as any)}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-800 rounded-xl text-white"
                >
                  <option value="Obra Gruesa">Obra Gruesa</option>
                  <option value="Instalaciones">Instalaciones</option>
                  <option value="Terminaciones">Terminaciones</option>
                  <option value="Fachada">Fachada</option>
                  <option value="Estructura">Estructura</option>
                </select>
              </div>

              <div>
                <label className="block text-slate-300 mb-1">Observaciones / Detalles</label>
                <textarea
                  rows={2}
                  placeholder="Detalle técnico de lo registrado..."
                  value={descripcion}
                  onChange={(e) => setDescripcion(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-800 rounded-xl text-white"
                />
              </div>

              <div className="p-4 border border-dashed border-slate-700 rounded-xl text-center bg-slate-900/50">
                <Upload className="w-5 h-5 mx-auto text-purple-400 mb-1" />
                <span className="text-[11px] text-slate-400 block">Selecciona o toma una foto desde tu cámara</span>
              </div>

              <div className="flex space-x-3 pt-3">
                <button
                  type="button"
                  onClick={() => setModalSubirFoto(false)}
                  className="w-1/2 py-2.5 bg-slate-800 text-slate-300 rounded-xl font-semibold"
                >
                  Cancelar
                </button>
                <button
                  type="submit"
                  className="w-1/2 py-2.5 bg-purple-600 hover:bg-purple-500 text-white rounded-xl font-semibold"
                >
                  Guardar Foto
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
