'use client';

import { useState, useEffect } from 'react';
import { Lead } from '@/lib/db';

const STATUS_COLUMNS = [
  { id: 'Nuevo', name: 'Nuevos 📥', color: 'var(--accent)' },
  { id: 'Calificado', name: 'Calificados 🔍', color: '#38bdf8' },
  { id: 'Demo Agendada', name: 'Demo Agendada 📅', color: '#f59e0b' },
  { id: 'Contrató', name: 'Contrató 🎉', color: '#10b981' }
];

export function LeadsPanel() {
  const [leads, setLeads] = useState<Lead[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [updatingId, setUpdatingId] = useState<number | null>(null);

  const fetchLeads = async () => {
    try {
      const res = await fetch('/api/leads');
      const data = await res.json();
      setLeads(data.leads || []);
    } catch (err) {
      console.error('Error fetching leads:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLeads();
    const interval = setInterval(fetchLeads, 4000);
    return () => clearInterval(interval);
  }, []);

  const handleUpdateStatus = async (id: number, status: string) => {
    setUpdatingId(id);
    try {
      const res = await fetch('/api/leads', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'update_status', id, status }),
      });
      if (res.ok) {
        setLeads((prev) =>
          prev.map((l) => (l.id === id ? { ...l, status, updated_at: Math.floor(Date.now() / 1000) } : l))
        );
      }
    } catch (err) {
      console.error('Error updating status:', err);
    } finally {
      setUpdatingId(null);
    }
  };

  const handleDeleteLead = async (id: number) => {
    if (!confirm('¿Estás seguro de que deseas eliminar este prospecto?')) return;
    setUpdatingId(id);
    try {
      const res = await fetch('/api/leads', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'delete', id }),
      });
      if (res.ok) {
        setLeads((prev) => prev.filter((l) => l.id !== id));
      }
    } catch (err) {
      console.error('Error deleting lead:', err);
    } finally {
      setUpdatingId(null);
    }
  };

  // Filtrar leads según la búsqueda
  const filteredLeads = leads.filter((l) => {
    const s = search.toLowerCase().trim();
    if (!s) return true;
    return (
      (l.name && l.name.toLowerCase().includes(s)) ||
      l.phone.includes(s) ||
      (l.email && l.email.toLowerCase().includes(s)) ||
      (l.agency_name && l.agency_name.toLowerCase().includes(s))
    );
  });

  if (loading && leads.length === 0) {
    return (
      <div className="leads-container" style={{ padding: '24px', flex: 1, display: 'flex', flexDirection: 'column', gap: '20px' }}>
        <div className="skeleton" style={{ height: '40px', width: '200px', borderRadius: '8px' }} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '16px', flex: 1 }}>
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="skeleton" style={{ height: '350px', borderRadius: '12px' }} />
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="leads-container" style={{ display: 'flex', flexDirection: 'column', flex: 1, height: '100%', overflow: 'hidden' }}>
      {/* Header del Panel */}
      <div className="leads-header" style={{ padding: '20px 24px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '16px' }}>
        <div>
          <h2 style={{ fontSize: '1.25rem', fontWeight: 700, margin: 0, display: 'flex', alignItems: 'center', gap: '8px' }}>
            💼 Pipeline de Prospectos B2B
            <span className="badge-count" style={{ fontSize: '0.8rem', padding: '2px 8px' }}>
              {filteredLeads.length}
            </span>
          </h2>
          <p style={{ fontSize: '0.75rem', color: 'var(--text-muted)', margin: '4px 0 0 0' }}>
            Prospectos comerciales calificados automáticamente por la IA desde WhatsApp.
          </p>
        </div>

        {/* Buscador */}
        <div className="search-epic" style={{ width: '280px', margin: 0 }}>
          <svg fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
            <path strokeLinecap="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input
            type="search"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Buscar prospecto por nombre, agencia..."
            style={{ width: '100%' }}
          />
        </div>
      </div>

      {/* Grid del Kanban */}
      <div className="leads-board" style={{ padding: '20px 24px', display: 'flex', gap: '16px', flex: 1, overflowX: 'auto', overflowY: 'hidden', alignItems: 'stretch' }}>
        {STATUS_COLUMNS.map((col) => {
          const colLeads = filteredLeads.filter((l) => l.status === col.id);

          return (
            <div
              key={col.id}
              className="panel"
              style={{
                flex: '1 0 280px',
                maxWidth: '350px',
                display: 'flex',
                flexDirection: 'column',
                borderRadius: '12px',
                background: 'var(--panel-bg)',
                border: '1px solid var(--border)',
                height: '100%',
                overflow: 'hidden'
              }}
            >
              {/* Header Columna */}
              <div
                style={{
                  padding: '14px 16px',
                  borderBottom: '1px solid var(--border)',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  fontWeight: 600,
                  fontSize: '0.85rem'
                }}
              >
                <span style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: col.color }} />
                  {col.name}
                </span>
                <span style={{ fontSize: '0.75rem', background: 'var(--border-strong)', color: 'var(--text)', padding: '2px 6px', borderRadius: '6px' }}>
                  {colLeads.length}
                </span>
              </div>

              {/* Lista de Tarjetas */}
              <div
                style={{
                  padding: '12px',
                  display: 'flex',
                  flexDirection: 'column',
                  gap: '12px',
                  flex: 1,
                  overflowY: 'auto'
                }}
              >
                {colLeads.length === 0 ? (
                  <div style={{ textAlign: 'center', padding: '30px 10px', color: 'var(--text-muted)', fontSize: '0.75rem', border: '1px dashed var(--border)', borderRadius: '8px' }}>
                    Sin prospectos en esta etapa
                  </div>
                ) : (
                  colLeads.map((lead) => {
                    const clientName = lead.name || 'Prospecto sin Nombre';
                    const cleanPhone = lead.phone.split('@')[0];
                    return (
                      <div
                        key={lead.id}
                        className="lead-card"
                        style={{
                          background: 'var(--bg)',
                          border: '1px solid var(--border-strong)',
                          borderRadius: '8px',
                          padding: '14px',
                          display: 'flex',
                          flexDirection: 'column',
                          gap: '10px',
                          position: 'relative',
                          opacity: updatingId === lead.id ? 0.6 : 1,
                          boxShadow: '0 2px 4px rgba(0,0,0,0.02)'
                        }}
                      >
                        {/* Botón de Borrar */}
                        <button
                          type="button"
                          onClick={() => handleDeleteLead(lead.id)}
                          style={{
                            position: 'absolute',
                            top: '12px',
                            right: '12px',
                            background: 'transparent',
                            border: 'none',
                            color: 'var(--rose)',
                            fontSize: '0.85rem',
                            cursor: 'pointer',
                            padding: '4px',
                            borderRadius: '4px',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center'
                          }}
                          title="Eliminar prospecto"
                          onMouseOver={(e) => e.currentTarget.style.background = 'rgba(244,63,94,0.1)'}
                          onMouseOut={(e) => e.currentTarget.style.background = 'transparent'}
                        >
                          ✕
                        </button>

                        {/* Nombre del Prospecto */}
                        <div>
                          <div style={{ fontWeight: 700, fontSize: '0.85rem', color: 'var(--text)', paddingRight: '20px' }}>
                            {clientName}
                          </div>
                          <div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', marginTop: '2px' }}>
                            📱 {cleanPhone}
                          </div>
                        </div>

                        {/* Información Extraída */}
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', borderTop: '1px solid var(--border)', paddingTop: '10px', fontSize: '0.75rem' }}>
                          {lead.agency_name && (
                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '6px' }}>
                              <span>🏢</span>
                              <strong>{lead.agency_name}</strong>
                            </div>
                          )}
                          {lead.email && (
                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '6px', wordBreak: 'break-all' }}>
                              <span>✉️</span>
                              <span style={{ color: 'var(--accent)' }}>{lead.email}</span>
                            </div>
                          )}
                          {lead.current_system && (
                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '6px' }}>
                              <span>📊</span>
                              <span>Usa: <strong style={{ color: 'var(--violet)' }}>{lead.current_system}</strong></span>
                            </div>
                          )}
                          {lead.booking_volume && (
                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '6px' }}>
                              <span>📈</span>
                              <span>Reservas: <strong>{lead.booking_volume}</strong></span>
                            </div>
                          )}
                        </div>

                        {/* Selector de Estado */}
                        <div style={{ borderTop: '1px solid var(--border)', paddingTop: '8px', marginTop: '2px' }}>
                          <label style={{ fontSize: '0.65rem', fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', display: 'block', marginBottom: '4px' }}>
                            Mover a etapa:
                          </label>
                          <select
                            value={lead.status}
                            onChange={(e) => handleUpdateStatus(lead.id, e.target.value)}
                            disabled={updatingId === lead.id}
                            style={{
                              width: '100%',
                              padding: '6px',
                              borderRadius: '6px',
                              background: 'var(--panel-bg)',
                              border: '1px solid var(--border-strong)',
                              color: 'var(--text)',
                              fontSize: '0.72rem',
                              fontWeight: 600,
                              cursor: 'pointer'
                            }}
                          >
                            {STATUS_COLUMNS.map((sc) => (
                              <option key={sc.id} value={sc.id}>
                                {sc.id}
                              </option>
                            ))}
                          </select>
                        </div>
                      </div>
                    );
                  })
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
