'use client';

import React, { useState, useEffect, use } from 'react';
import Link from 'next/link';
import { 
  INITIAL_OBRAS, INITIAL_USUARIOS, INITIAL_PLANOS, 
  INITIAL_RDIS, INITIAL_REUNIONES, INITIAL_FOTOS, INITIAL_INSPECCIONES 
} from '@/lib/data/mockData';
import { RolType, Usuario } from '@/types';
import { 
  Building2, FileText, HelpCircle, Calendar, Image as ImageIcon, 
  ShieldCheck, LogOut, CheckCircle2, AlertCircle, Clock, Plus, 
  Users, Layers, ArrowUpRight, HardHat, FileSpreadsheet, Eye
} from 'lucide-react';

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

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

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

  // Estado de usuario y rol activo en la sesión de esta obra
  const [activeUser, setActiveUser] = useState<Usuario>(INITIAL_USUARIOS[0]); // Default Arq. Oscar Silva
  const [activeRol, setActiveRol] = useState<RolType>('arquitecto_admin');

  useEffect(() => {
    const sessionStr = localStorage.getItem('sigueobras_session');
    if (sessionStr) {
      try {
        const session = JSON.parse(sessionStr);
        if (session.usuario) {
          setActiveUser(session.usuario);
          setActiveRol(session.usuario.rol);
        }
      } catch (e) {
        console.error(e);
      }
    }
  }, []);

  const cambiarRolSimulado = (nuevoRol: RolType) => {
    const userCoincidente = INITIAL_USUARIOS.find(u => u.obraId === obraId && u.rol === nuevoRol) || {
      id: `sim-${nuevoRol}`,
      nombre: nuevoRol === 'arquitecto_admin' ? 'Arq. Oscar Silva' : `Usuario Simulado (${nuevoRol.toUpperCase()})`,
      correo: `${nuevoRol}@demo.cl`,
      rol: nuevoRol,
      estado: 'activo',
      fechaCreacion: '2026-07-26'
    };
    setActiveUser(userCoincidente as Usuario);
    setActiveRol(nuevoRol);
  };

  const planosObra = INITIAL_PLANOS.filter(p => p.obraId === obraId);
  const rdisObra = INITIAL_RDIS.filter(r => r.obraId === obraId);
  const rdisPendientes = rdisObra.filter(r => r.estado === 'pendiente');
  const reunionesObra = INITIAL_REUNIONES.filter(r => r.obraId === obraId);
  const fotosObra = INITIAL_FOTOS.filter(f => f.obraId === obraId);

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 flex flex-col justify-between selection:bg-sky-500 selection:text-white">
      {/* Navbar Superior */}
      <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="/" className="p-2 bg-gradient-to-tr from-sky-600 to-amber-500 rounded-lg text-white font-bold">
              <Building2 className="w-5 h-5" />
            </Link>
            <div>
              <h1 className="font-bold text-white text-base leading-tight flex items-center space-x-2">
                <span>{obra.nombre}</span>
                <span className="text-[10px] px-2 py-0.5 rounded-full bg-sky-950 text-sky-400 border border-sky-800">
                  {obra.porcentajeAvance}% avance
                </span>
              </h1>
              <span className="text-xs text-slate-400 block">{obra.direccion}, {obra.comuna}</span>
            </div>
          </div>

          {/* Selector interactivo de Roles */}
          <div className="flex items-center space-x-3">
            <div className="hidden md:flex items-center space-x-1.5 bg-slate-950 p-1.5 rounded-xl border border-slate-800 text-xs">
              <span className="text-slate-500 text-[10px] uppercase font-mono px-2">Vista Rol:</span>
              <button
                onClick={() => cambiarRolSimulado('arquitecto_admin')}
                className={`px-2 py-1 rounded-lg font-medium transition-all ${activeRol === 'arquitecto_admin' ? 'bg-amber-500 text-slate-950 font-bold' : 'text-slate-400 hover:text-white'}`}
              >
                Admin (Oscar)
              </button>
              <button
                onClick={() => cambiarRolSimulado('propietario')}
                className={`px-2 py-1 rounded-lg font-medium transition-all ${activeRol === 'propietario' ? 'bg-blue-600 text-white font-bold' : 'text-slate-400 hover:text-white'}`}
              >
                Propietario
              </button>
              <button
                onClick={() => cambiarRolSimulado('constructor')}
                className={`px-2 py-1 rounded-lg font-medium transition-all ${activeRol === 'constructor' ? 'bg-orange-600 text-white font-bold' : 'text-slate-400 hover:text-white'}`}
              >
                Constructor
              </button>
              <button
                onClick={() => cambiarRolSimulado('ito')}
                className={`px-2 py-1 rounded-lg font-medium transition-all ${activeRol === 'ito' ? 'bg-emerald-600 text-white font-bold' : 'text-slate-400 hover:text-white'}`}
              >
                ITO
              </button>
              <button
                onClick={() => cambiarRolSimulado('externo')}
                className={`px-2 py-1 rounded-lg font-medium transition-all ${activeRol === 'externo' ? 'bg-purple-600 text-white font-bold' : 'text-slate-400 hover:text-white'}`}
              >
                Externo
              </button>
            </div>

            <div className="flex items-center space-x-2 border-l border-slate-800 pl-3">
              <div className="text-right hidden sm:block">
                <div className="text-xs font-semibold text-white">{activeUser.nombre}</div>
                <div className="text-[10px] text-amber-400 font-mono uppercase">{activeRol}</div>
              </div>
              <Link href={`/obra/${obraId}/login`} className="p-2 text-slate-400 hover:text-white rounded-lg hover:bg-slate-800">
                <LogOut className="w-4 h-4" />
              </Link>
            </div>
          </div>
        </div>

        {/* Navigation Tabs */}
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 border-t border-slate-800/80 flex items-center space-x-1 overflow-x-auto text-xs py-1">
          <Link href={`/obra/${obraId}/dashboard`} className="px-3 py-2 rounded-lg bg-sky-950/80 text-sky-400 font-semibold flex items-center space-x-1.5 shrink-0 border border-sky-800/60">
            <Building2 className="w-3.5 h-3.5" />
            <span>Dashboard KPI</span>
          </Link>
          <Link href={`/obra/${obraId}/documentos`} className="px-3 py-2 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800/60 flex items-center space-x-1.5 shrink-0 transition-colors">
            <FileText className="w-3.5 h-3.5 text-blue-400" />
            <span>Planos y Documentos ({planosObra.length})</span>
          </Link>
          <Link href={`/obra/${obraId}/rdis`} className="px-3 py-2 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800/60 flex items-center space-x-1.5 shrink-0 transition-colors">
            <HelpCircle className="w-3.5 h-3.5 text-amber-400" />
            <span>RDIs ({rdisPendientes.length} pend.)</span>
          </Link>
          <Link href={`/obra/${obraId}/reuniones`} className="px-3 py-2 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800/60 flex items-center space-x-1.5 shrink-0 transition-colors">
            <Calendar className="w-3.5 h-3.5 text-emerald-400" />
            <span>Reuniones y Actas</span>
          </Link>
          <Link href={`/obra/${obraId}/fotos`} className="px-3 py-2 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800/60 flex items-center space-x-1.5 shrink-0 transition-colors">
            <ImageIcon className="w-3.5 h-3.5 text-purple-400" />
            <span>Galería de Fotos</span>
          </Link>
          {activeRol === 'arquitecto_admin' && (
            <Link href={`/admin/obras/${obraId}/usuarios`} className="px-3 py-2 rounded-lg text-amber-400 hover:bg-amber-950/60 flex items-center space-x-1.5 shrink-0 border border-amber-800/50 ml-auto font-semibold">
              <Users className="w-3.5 h-3.5 text-amber-400" />
              <span>Panel Oculto Usuarios</span>
            </Link>
          )}
        </div>
      </header>

      {/* Body del Dashboard Adaptativo */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 flex-1 w-full space-y-8">
        <div className="p-6 rounded-2xl bg-gradient-to-r from-slate-900 via-slate-900 to-slate-950 border border-slate-800 relative overflow-hidden">
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center space-y-4 sm:space-y-0">
            <div>
              <span className="text-xs font-mono uppercase tracking-wider text-sky-400 font-bold">
                VISTA ADAPTATIVA PARA: {activeRol.toUpperCase()}
              </span>
              <h2 className="text-2xl font-bold text-white mt-1">
                Bienvenido(a), {activeUser.nombre}
              </h2>
              <p className="text-slate-400 text-xs mt-1">
                {activeRol === 'arquitecto_admin' && 'Como Arquitecto Principal (Arq. Oscar Silva), tienes control completo para administrar usuarios, responder RDIs y validar entregables.'}
                {activeRol === 'propietario' && 'Visualización ejecutiva de avances, galería fotográfica, actas de reuniones y aprobación de hitos.'}
                {activeRol === 'constructor' && 'Gestión de requerimientos RDIs de terreno, actualización de fotos y carga de actas de obra.'}
                {activeRol === 'ito' && 'Supervisión de calidad, generación de checklists de inspección y aprobación de entregables.'}
                {activeRol === 'externo' && 'Acceso acotado exclusivamente a las carpetas y especialidades autorizadas.'}
              </p>
            </div>
            
            <div className="flex items-center space-x-3">
              <Link 
                href={`/obra/${obraId}/rdis`} 
                className="btn-primary text-xs px-4 py-2.5 rounded-xl font-bold flex items-center space-x-2"
              >
                <Plus className="w-4 h-4" />
                <span>Nuevo RDI / Requerimiento</span>
              </Link>
            </div>
          </div>
        </div>

        {/* Tarjetas KPI Principales */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
          <div className="glass-card p-5 rounded-2xl border border-slate-800">
            <div className="flex items-center justify-between mb-3">
              <span className="text-xs text-slate-400 font-medium">Avance Físico</span>
              <Building2 className="w-4 h-4 text-sky-400" />
            </div>
            <div className="text-3xl font-black text-white">{obra.porcentajeAvance}%</div>
            <div className="w-full bg-slate-800 h-1.5 rounded-full mt-2 overflow-hidden">
              <div className="bg-sky-500 h-full rounded-full" style={{ width: `${obra.porcentajeAvance}%` }} />
            </div>
          </div>

          <div className="glass-card p-5 rounded-2xl border border-slate-800">
            <div className="flex items-center justify-between mb-3">
              <span className="text-xs text-slate-400 font-medium">Planos Vigentes</span>
              <FileText className="w-4 h-4 text-blue-400" />
            </div>
            <div className="text-3xl font-black text-white">{planosObra.length}</div>
            <div className="text-[11px] text-slate-500 mt-1">Último subido: v2.1 (ARQ-101)</div>
          </div>

          <div className="glass-card p-5 rounded-2xl border border-slate-800">
            <div className="flex items-center justify-between mb-3">
              <span className="text-xs text-slate-400 font-medium">RDIs Pendientes</span>
              <HelpCircle className="w-4 h-4 text-amber-400" />
            </div>
            <div className="text-3xl font-black text-amber-400">{rdisPendientes.length}</div>
            <div className="text-[11px] text-slate-500 mt-1">1 RDI crítico requiere respuesta</div>
          </div>

          <div className="glass-card p-5 rounded-2xl border border-slate-800">
            <div className="flex items-center justify-between mb-3">
              <span className="text-xs text-slate-400 font-medium">Actas Registradas</span>
              <Calendar className="w-4 h-4 text-emerald-400" />
            </div>
            <div className="text-3xl font-black text-white">{reunionesObra.length}</div>
            <div className="text-[11px] text-slate-500 mt-1">Próxima reunión: Jueves 10:00 AM</div>
          </div>
        </div>

        {/* Sección RDIs Urgentes */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="glass-panel lg:col-span-2 p-6 rounded-2xl border border-slate-800">
            <div className="flex items-center justify-between mb-5">
              <h3 className="text-base font-bold text-white flex items-center space-x-2">
                <HelpCircle className="w-5 h-5 text-amber-400" />
                <span>Requerimientos de Información (RDIs) Activos</span>
              </h3>
              <Link href={`/obra/${obraId}/rdis`} className="text-xs text-sky-400 hover:underline">
                Ver todos ({rdisObra.length})
              </Link>
            </div>

            <div className="space-y-3">
              {rdisObra.map((rdi) => (
                <div key={rdi.id} className="p-4 bg-slate-900/80 rounded-xl border border-slate-800/80 flex flex-col sm:flex-row justify-between items-start sm:items-center space-y-2 sm:space-y-0">
                  <div>
                    <div className="flex items-center space-x-2 mb-1">
                      <span className="text-xs font-mono font-bold text-amber-400">{rdi.codigo}</span>
                      <span className={`px-2 py-0.5 rounded text-[10px] font-bold ${
                        rdi.prioridad === 'alta' ? 'bg-red-950 text-red-300 border border-red-800' : 'bg-slate-800 text-slate-300'
                      }`}>
                        {rdi.prioridad.toUpperCase()}
                      </span>
                      <span className="text-xs font-semibold text-white">{rdi.asunto}</span>
                    </div>
                    <div className="text-xs text-slate-400">
                      Emitido por <span className="text-slate-300">{rdi.deUsuarioNombre}</span> • Límite: {rdi.fechaLimite}
                    </div>
                  </div>

                  <span className={`px-2.5 py-1 rounded-full text-xs font-semibold shrink-0 ${
                    rdi.estado === 'pendiente' ? 'bg-amber-950 text-amber-300 border border-amber-700/60' : 'bg-emerald-950 text-emerald-300'
                  }`}>
                    {rdi.estado}
                  </span>
                </div>
              ))}
            </div>
          </div>

          <div className="glass-panel p-6 rounded-2xl border border-slate-800">
            <div className="flex items-center justify-between mb-5">
              <h3 className="text-base font-bold text-white flex items-center space-x-2">
                <ImageIcon className="w-5 h-5 text-purple-400" />
                <span>Últimas Fotos de Terreno</span>
              </h3>
              <Link href={`/obra/${obraId}/fotos`} className="text-xs text-sky-400 hover:underline">
                Galería completa
              </Link>
            </div>

            <div className="space-y-4">
              {fotosObra.map((foto) => (
                <div key={foto.id} className="group relative rounded-xl overflow-hidden border border-slate-800">
                  <img src={foto.imageUrl} alt={foto.titulo} className="w-full h-36 object-cover group-hover:scale-105 transition-transform duration-300" />
                  <div className="absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-950/20 to-transparent p-3 flex flex-col justify-end">
                    <span className="text-[10px] font-bold text-amber-400">{foto.etiqueta} • {foto.fecha}</span>
                    <h4 className="text-xs font-bold text-white line-clamp-1">{foto.titulo}</h4>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
