'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { INITIAL_OBRAS, INITIAL_USUARIOS } from '@/lib/data/mockData';
import { Obra } from '@/types';
import { 
  Building2, Plus, Users, ShieldCheck, FolderKanban, LogOut, 
  MapPin, Calendar, ArrowRight, Eye, UserPlus, KeyRound, CheckCircle2
} from 'lucide-react';

export default function AdminDashboardPage() {
  const [obras, setObras] = useState<Obra[]>(INITIAL_OBRAS);
  const [modalNuevaObra, setModalNuevaObra] = useState(false);
  const [notificacion, setNotificacion] = useState('');

  // Form state para crear obra
  const [nombreObra, setNombreObra] = useState('');
  const [direccionObra, setDireccionObra] = useState('');
  const [comunaObra, setComunaObra] = useState('');
  const [ciudadObra, setCiudadObra] = useState('Santiago');
  const [presupuestoObra, setPresupuestoObra] = useState('$ 2.500.000.000 CLP');

  const handleCrearObra = (e: React.FormEvent) => {
    e.preventDefault();
    const nuevaObraObj: Obra = {
      id: `obra-${Date.now()}`,
      nombre: nombreObra,
      direccion: direccionObra,
      comuna: comunaObra,
      ciudad: ciudadObra,
      imagen: 'https://images.unsplash.com/photo-1541888946425-d0fbb186a5b3?auto=format&fit=crop&w=800&q=80',
      fechaInicio: new Date().toISOString().split('T')[0],
      fechaFinEstimada: '2027-12-31',
      porcentajeAvance: 0,
      estado: 'planificacion',
      creadoPor: 'user-admin',
      presupuestoTotal: presupuestoObra,
      rolesDisponibles: ['propietario', 'constructor', 'ito']
    };

    setObras([nuevaObraObj, ...obras]);
    setModalNuevaObra(false);
    setNombreObra('');
    setDireccionObra('');
    setComunaObra('');
    setNotificacion(`Obra "${nuevaObraObj.nombre}" creada con éxito.`);
    setTimeout(() => setNotificacion(''), 4000);
  };

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 flex flex-col justify-between selection:bg-amber-500 selection:text-white">
      {/* Top Navbar */}
      <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">
            <div className="p-2 bg-amber-500 text-slate-950 rounded-lg font-bold">
              <ShieldCheck className="w-5 h-5" />
            </div>
            <div>
              <span className="font-bold text-white text-base">Panel de Control Global</span>
              <span className="text-xs text-amber-400 block -mt-1 font-medium">Arq. Oscar Silva (Administrador Único)</span>
            </div>
          </div>

          <div className="flex items-center space-x-4">
            <button
              onClick={() => setModalNuevaObra(true)}
              className="bg-amber-500 hover:bg-amber-400 text-slate-950 px-4 py-2 rounded-xl text-xs font-bold flex items-center space-x-1.5 transition-all shadow-md shadow-amber-500/20"
            >
              <Plus className="w-4 h-4" />
              <span>Crear Nueva Obra</span>
            </button>
            <Link href="/" className="text-xs text-slate-400 hover:text-white flex items-center space-x-1">
              <LogOut className="w-4 h-4" />
              <span>Cerrar Sesión</span>
            </Link>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10 flex-1 w-full">
        {notificacion && (
          <div className="mb-6 p-4 bg-emerald-950/80 border border-emerald-800 rounded-xl text-emerald-300 text-sm flex items-center space-x-2">
            <CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />
            <span>{notificacion}</span>
          </div>
        )}

        {/* Global KPIs Header */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-5 mb-10">
          <div className="glass-panel p-5 rounded-2xl border border-slate-800 flex items-center space-x-4">
            <div className="p-3 bg-sky-950 text-sky-400 rounded-xl border border-sky-800/50">
              <Building2 className="w-6 h-6" />
            </div>
            <div>
              <div className="text-2xl font-black text-white">{obras.length}</div>
              <div className="text-xs text-slate-400 font-medium">Obras Activas Gestionadas</div>
            </div>
          </div>

          <div className="glass-panel p-5 rounded-2xl border border-slate-800 flex items-center space-x-4">
            <div className="p-3 bg-amber-950 text-amber-400 rounded-xl border border-amber-800/50">
              <Users className="w-6 h-6" />
            </div>
            <div>
              <div className="text-2xl font-black text-white">{INITIAL_USUARIOS.length}</div>
              <div className="text-xs text-slate-400 font-medium">Usuarios Registrados en Sistema</div>
            </div>
          </div>

          <div className="glass-panel p-5 rounded-2xl border border-slate-800 flex items-center space-x-4">
            <div className="p-3 bg-emerald-950 text-emerald-400 rounded-xl border border-emerald-800/50">
              <ShieldCheck className="w-6 h-6" />
            </div>
            <div>
              <div className="text-2xl font-black text-white">100%</div>
              <div className="text-xs text-slate-400 font-medium">Control de Permisos por Obra</div>
            </div>
          </div>
        </div>

        <div className="flex items-center justify-between mb-6">
          <div>
            <h2 className="text-xl font-bold text-white">Todas tus Obras en Paralelo</h2>
            <p className="text-slate-400 text-xs">Selecciona una obra para administrar sus usuarios o ingresar al módulo completo.</p>
          </div>
        </div>

        {/* Listado de Obras */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {obras.map((obra) => {
            const countUsersObra = INITIAL_USUARIOS.filter(u => u.obraId === obra.id).length;

            return (
              <div key={obra.id} className="glass-card rounded-2xl overflow-hidden border border-slate-800 flex flex-col justify-between">
                <div>
                  <div className="relative h-40 w-full bg-slate-900">
                    <img src={obra.imagen} alt={obra.nombre} className="w-full h-full object-cover" />
                    <div className="absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-950/30 to-transparent" />
                    
                    <span className="absolute top-3 right-3 px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-amber-950/90 text-amber-300 border border-amber-700">
                      {obra.presupuestoTotal}
                    </span>
                  </div>

                  <div className="p-5">
                    <h3 className="text-lg font-bold text-white mb-1">{obra.nombre}</h3>
                    <p className="text-xs text-slate-400 flex items-center space-x-1 mb-3">
                      <MapPin className="w-3.5 h-3.5 text-sky-400 shrink-0" />
                      <span>{obra.direccion}, {obra.comuna}</span>
                    </p>

                    <div className="flex items-center justify-between text-xs py-2 px-3 bg-slate-900/80 rounded-xl border border-slate-800 mb-4">
                      <span className="text-slate-400">Usuarios Asignados:</span>
                      <span className="font-bold text-slate-200">{countUsersObra} personas</span>
                    </div>
                  </div>
                </div>

                <div className="p-5 pt-0 space-y-2">
                  <Link
                    href={`/admin/obras/${obra.id}/usuarios`}
                    className="w-full bg-slate-800 hover:bg-slate-700 text-amber-300 font-semibold py-2.5 px-4 rounded-xl text-xs flex items-center justify-center space-x-2 border border-amber-500/20 transition-all"
                  >
                    <Users className="w-4 h-4 text-amber-400" />
                    <span>Panel Oculto de Usuarios ({countUsersObra})</span>
                  </Link>

                  <Link
                    href={`/obra/${obra.id}/dashboard`}
                    className="w-full bg-sky-600 hover:bg-sky-500 text-white font-semibold py-2.5 px-4 rounded-xl text-xs flex items-center justify-center space-x-2 transition-all shadow-md"
                  >
                    <Eye className="w-4 h-4" />
                    <span>Ingresar a Obra como Admin</span>
                  </Link>
                </div>
              </div>
            );
          })}
        </div>
      </main>

      {/* Modal Crear Nueva Obra */}
      {modalNuevaObra && (
        <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-lg w-full p-6 rounded-2xl border border-slate-800 shadow-2xl">
            <h3 className="text-lg font-bold text-white mb-1">Crear Nueva Obra de Construcción</h3>
            <p className="text-slate-400 text-xs mb-5">
              Define los datos principales. Luego podrás invitar y crear los usuarios para cada rol.
            </p>

            <form onSubmit={handleCrearObra} className="space-y-4">
              <div>
                <label className="block text-xs font-medium text-slate-300 mb-1">Nombre de la Obra</label>
                <input
                  type="text"
                  required
                  placeholder="ej. Torre Las Condes II"
                  value={nombreObra}
                  onChange={(e) => setNombreObra(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-800 rounded-xl text-white text-sm"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-medium text-slate-300 mb-1">Dirección</label>
                  <input
                    type="text"
                    required
                    placeholder="ej. Av. Apoquindo 4500"
                    value={direccionObra}
                    onChange={(e) => setDireccionObra(e.target.value)}
                    className="w-full px-3 py-2 bg-slate-900 border border-slate-800 rounded-xl text-white text-sm"
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-300 mb-1">Comuna</label>
                  <input
                    type="text"
                    required
                    placeholder="ej. Las Condes"
                    value={comunaObra}
                    onChange={(e) => setComunaObra(e.target.value)}
                    className="w-full px-3 py-2 bg-slate-900 border border-slate-800 rounded-xl text-white text-sm"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-medium text-slate-300 mb-1">Presupuesto Estimado</label>
                <input
                  type="text"
                  required
                  value={presupuestoObra}
                  onChange={(e) => setPresupuestoObra(e.target.value)}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-800 rounded-xl text-white text-sm"
                />
              </div>

              <div className="flex space-x-3 pt-3">
                <button
                  type="button"
                  onClick={() => setModalNuevaObra(false)}
                  className="w-1/2 py-2.5 bg-slate-800 hover:bg-slate-700 text-slate-300 font-semibold rounded-xl text-xs"
                >
                  Cancelar
                </button>
                <button
                  type="submit"
                  className="w-1/2 py-2.5 bg-amber-500 hover:bg-amber-400 text-slate-950 font-bold rounded-xl text-xs"
                >
                  Guardar Obra
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
