"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Search, Plus, Eye, Edit, Filter } from "lucide-react";

interface Socio {
  Id_cliente: number;
  rut_cliente: string;
  nombre_cliente: string;
  direccion: string;
  nombre_sector: string;
  estado_socio: number;
  nombre_estado: string;
}

export default function SociosPage() {
  const [socios, setSocios] = useState<Socio[]>([]);
  const [busqueda, setBusqueda] = useState("");
  const [sectorFiltro, setSectorFiltro] = useState("");
  const [sectores, setSectores] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

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

  const cargarDatos = async () => {
    try {
      const [sociosRes, sectoresRes] = await Promise.all([
        fetch("/api/socios"),
        fetch("/api/mantenedores/sectores")
      ]);
      setSocios(await sociosRes.json());
      setSectores(await sectoresRes.json());
    } catch (error) {
      console.error("Error al cargar datos:", error);
    } finally {
      setLoading(false);
    }
  };

  const filtrarSocios = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (busqueda) params.append("busqueda", busqueda);
      if (sectorFiltro) params.append("sector", sectorFiltro);
      
      const res = await fetch(`/api/socios?${params}`);
      setSocios(await res.json());
    } catch (error) {
      console.error("Error al filtrar:", error);
    } finally {
      setLoading(false);
    }
  };

  const getEstadoColor = (estado: number) => {
    switch (estado) {
      case 1: return "bg-green-100 text-green-800";
      case 2: return "bg-yellow-100 text-yellow-800";
      case 3: return "bg-orange-100 text-orange-800";
      case 4: return "bg-red-100 text-red-800";
      default: return "bg-gray-100 text-gray-800";
    }
  };

  return (
    <div>
      <div className="flex flex-col md:flex-row md:justify-between md:items-center mb-6 gap-4">
        <h1 className="page-title">Gestión de Socios</h1>
        <Link href="/socios/nuevo" className="btn-primary flex items-center justify-center gap-2 w-full md:w-auto">
          <Plus className="w-4 h-4" /> Nuevo Socio
        </Link>
      </div>

      <div className="card mb-6">
        <div className="flex flex-col md:flex-row md:flex-wrap gap-4">
          <div className="flex-1 min-w-0">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <input
                type="text"
                placeholder="Buscar por nombre o RUT..."
                value={busqueda}
                onChange={(e) => setBusqueda(e.target.value)}
                className="input-field pl-10 w-full"
              />
            </div>
          </div>
          <select
            value={sectorFiltro}
            onChange={(e) => setSectorFiltro(e.target.value)}
            className="input-field w-full md:w-48"
          >
            <option value="">Todos los sectores</option>
            {sectores.map((s) => (
              <option key={s.Id_sector} value={s.Id_sector}>{s.nombre_sector}</option>
            ))}
          </select>
          <button onClick={filtrarSocios} className="btn-primary flex items-center justify-center gap-2 w-full md:w-auto">
            <Filter className="w-4 h-4" /> Filtrar
          </button>
        </div>
      </div>

      <div className="card">
        {loading ? (
          <div className="text-center py-8 text-gray-500">Cargando...</div>
        ) : socios.length === 0 ? (
          <div className="text-center py-8 text-gray-500">No se encontraron socios</div>
        ) : (
          <>
            {/* Vista de Cards para Mobile */}
            <div className="md:hidden space-y-4">
              {socios.map((socio) => (
                <div
                  key={socio.Id_cliente}
                  className="bg-white border border-gray-200 rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow"
                >
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex-1">
                      <h3 className="text-lg font-semibold text-gray-900 mb-1">
                        {socio.nombre_cliente}
                      </h3>
                      <p className="text-sm font-mono text-gray-600">{socio.rut_cliente}</p>
                    </div>
                    <span className={`px-3 py-1 rounded-full text-xs font-medium whitespace-nowrap ${getEstadoColor(socio.estado_socio)}`}>
                      {socio.nombre_estado || `Estado ${socio.estado_socio}`}
                    </span>
                  </div>
                  
                  <div className="space-y-2 mb-4">
                    {socio.direccion && (
                      <div className="flex items-start gap-2">
                        <span className="text-xs text-gray-500 min-w-[80px]">Dirección:</span>
                        <span className="text-sm text-gray-700 flex-1">{socio.direccion}</span>
                      </div>
                    )}
                    {socio.nombre_sector && (
                      <div className="flex items-start gap-2">
                        <span className="text-xs text-gray-500 min-w-[80px]">Sector:</span>
                        <span className="text-sm text-gray-700 flex-1">{socio.nombre_sector}</span>
                      </div>
                    )}
                  </div>

                  <div className="flex gap-2 pt-3 border-t border-gray-100">
                    <Link
                      href={`/socios/${socio.Id_cliente}`}
                      className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition-colors text-sm font-medium"
                    >
                      <Eye className="w-4 h-4" />
                      Ver
                    </Link>
                    <Link
                      href={`/socios/${socio.Id_cliente}/editar`}
                      className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-gray-50 text-gray-700 rounded-lg hover:bg-gray-100 transition-colors text-sm font-medium"
                    >
                      <Edit className="w-4 h-4" />
                      Editar
                    </Link>
                  </div>
                </div>
              ))}
            </div>

            {/* Vista de Tabla para Desktop */}
            <div className="hidden md:block table-container">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 table-header">RUT</th>
                    <th className="px-6 py-3 table-header">Nombre</th>
                    <th className="px-6 py-3 table-header">Dirección</th>
                    <th className="px-6 py-3 table-header">Sector</th>
                    <th className="px-6 py-3 table-header">Estado</th>
                    <th className="px-6 py-3 table-header">Acciones</th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {socios.map((socio) => (
                    <tr key={socio.Id_cliente} className="hover:bg-gray-50">
                      <td className="table-cell font-mono">{socio.rut_cliente}</td>
                      <td className="table-cell font-medium">{socio.nombre_cliente}</td>
                      <td className="table-cell">{socio.direccion}</td>
                      <td className="table-cell">{socio.nombre_sector}</td>
                      <td className="table-cell">
                        <span className={`px-2 py-1 rounded-full text-xs font-medium ${getEstadoColor(socio.estado_socio)}`}>
                          {socio.nombre_estado || `Estado ${socio.estado_socio}`}
                        </span>
                      </td>
                      <td className="table-cell">
                        <div className="flex gap-2">
                          <Link href={`/socios/${socio.Id_cliente}`} className="text-blue-600 hover:text-blue-800">
                            <Eye className="w-4 h-4" />
                          </Link>
                          <Link href={`/socios/${socio.Id_cliente}/editar`} className="text-gray-600 hover:text-gray-800">
                            <Edit className="w-4 h-4" />
                          </Link>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}
        <div className="mt-4 text-sm text-gray-500">
          Total: {socios.length} socios
        </div>
      </div>
    </div>
  );
}
