'use client';

import React, { useState } from 'react';
import {
  FiVideo,
  FiArrowRight,
  FiXCircle,
  FiUserPlus,
  FiCopy,
  FiCheck,
  FiMoreVertical,
  FiUsers,
} from 'react-icons/fi';
import toast from 'react-hot-toast';

// Loose enough to survive backend variations
export interface MeetingRowData {
  id: number;
  title: string;
  room_code?: string;
  roomCode?: string;
  code?: string;
  scheduled_at?: string;
  scheduledAt?: string;
  created_at?: string;
  createdAt?: string;
  status?: 'live' | 'scheduled' | 'ended' | string;
  is_active?: boolean;
  isActive?: boolean;
  host_name?: string;
  hostName?: string;
  host?: { name?: string; firstName?: string; lastName?: string; email?: string };
  participant_count?: number;
  participantCount?: number;
  company_name?: string;
  companyName?: string;
}

interface Props {
  row: MeetingRowData;
  onJoin: (code: string) => void;
  onEnd: (row: MeetingRowData) => void;
  onInvite?: (row: MeetingRowData) => void;
}

// ─── Helpers ─────────────────────────────────────────────────────────────
function getCode(m: MeetingRowData): string {
  return m.room_code || m.roomCode || m.code || '';
}
function getScheduled(m: MeetingRowData): string | undefined {
  return m.scheduled_at || m.scheduledAt || m.created_at || m.createdAt;
}
function getHost(m: MeetingRowData): string {
  if (m.host_name) return m.host_name;
  if (m.hostName) return m.hostName;
  if (m.host) {
    const n = `${m.host.firstName ?? ''} ${m.host.lastName ?? ''}`.trim();
    if (n) return n;
    if (m.host.name) return m.host.name;
    if (m.host.email) return m.host.email;
  }
  return '';
}
function getParticipantCount(m: MeetingRowData): number {
  return m.participant_count ?? m.participantCount ?? 0;
}
function computeStatus(m: MeetingRowData): 'live' | 'scheduled' | 'ended' {
  if (m.status === 'live' || m.status === 'scheduled' || m.status === 'ended') {
    return m.status;
  }
  if (m.is_active === false || m.isActive === false) return 'ended';
  if (m.is_active === true || m.isActive === true) return 'live';
  const s = getScheduled(m);
  if (s) {
    const t = new Date(s).getTime();
    const now = Date.now();
    if (now - t > 2 * 60 * 60 * 1000) return 'ended';
    if (now < t) return 'scheduled';
  }
  return 'scheduled';
}
function initials(name: string): string {
  return (
    name
      .split(/\s+/)
      .filter(Boolean)
      .slice(0, 2)
      .map((s) => s.charAt(0).toUpperCase())
      .join('') || '—'
  );
}
function formatDateTime(iso?: string): {
  date: string;
  time: string;
  hint?: string;
} {
  if (!iso) return { date: '—', time: '' };
  const d = new Date(iso);
  const day = String(d.getDate()).padStart(2, '0');
  const month = d.toLocaleString('en-US', { month: 'short' });
  const year = String(d.getFullYear()).slice(2);
  let h = d.getHours();
  const m = String(d.getMinutes()).padStart(2, '0');
  const ampm = h >= 12 ? 'PM' : 'AM';
  h = h % 12 || 12;
  const time = `${String(h).padStart(2, '0')}.${m}${ampm}`;

  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const target = new Date(iso);
  target.setHours(0, 0, 0, 0);
  const diff = Math.round(
    (target.getTime() - today.getTime()) / (1000 * 60 * 60 * 24),
  );
  let hint: string | undefined;
  if (diff === 0) hint = 'Today';
  else if (diff === 1) hint = 'Tomorrow';
  else if (diff === -1) hint = '1d ago';
  else if (diff > 1 && diff <= 30) hint = `in ${diff}d`;
  else if (diff < -1 && diff >= -30) hint = `${Math.abs(diff)}d ago`;

  return { date: `${day} ${month} ${year}`, time, hint };
}

// Consistent color for a host name so their avatar is recognizable
function colorFor(seed: string): { bg: string; text: string } {
  const palette = [
    { bg: '#7c3aed', text: '#fff' },
    { bg: '#0891b2', text: '#fff' },
    { bg: '#16a34a', text: '#fff' },
    { bg: '#d97706', text: '#fff' },
    { bg: '#dc2626', text: '#fff' },
    { bg: '#be185d', text: '#fff' },
    { bg: '#0f766e', text: '#fff' },
    { bg: '#4a0080', text: '#fff' },
  ];
  let h = 0;
  for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) >>> 0;
  return palette[h % palette.length];
}

// ─── Config ──────────────────────────────────────────────────────────────
const CODE_COLORS = {
  live: { text: '#16a34a', badgeBg: '#dcfce7', badgeText: '#166534' },
  scheduled: { text: '#7c3aed', badgeBg: '#f3eefb', badgeText: '#6d28d9' },
  ended: { text: '#64748b', badgeBg: '#f1f5f9', badgeText: '#475569' },
};
const STATUS_CONFIG = {
  live: { label: 'Live', bg: '#dcfce7', text: '#166534', dot: '#22c55e' },
  scheduled: {
    label: 'Scheduled',
    bg: '#fef3c7',
    text: '#92400e',
    dot: '#f59e0b',
  },
  ended: { label: 'Ended', bg: '#f1f5f9', text: '#64748b', dot: '#94a3b8' },
};

// ═════════════════════════════════════════════════════════════════════════
// Component — renders as <tr> to fit inside the parent <table>
// ═════════════════════════════════════════════════════════════════════════
export default function MeetingRow({ row, onJoin, onEnd, onInvite }: Props) {
  const code = getCode(row);
  const host = getHost(row);
  const scheduled = getScheduled(row);
  const status = computeStatus(row);
  const dt = formatDateTime(scheduled);
  const participants = getParticipantCount(row);
  const codeColors = CODE_COLORS[status];
  const statusMeta = STATUS_CONFIG[status];
  const hostColor = host ? colorFor(host) : { bg: '#e2e8f0', text: '#64748b' };

  const [copied, setCopied] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

  const isEnded = status === 'ended';
  const isLive = status === 'live';

  // Split title into "COMPANY — REF" if possible
  const [company, ref] = React.useMemo(() => {
    if (!row.title) return ['', ''];
    if (row.company_name || row.companyName) {
      return [row.company_name ?? row.companyName ?? '', row.title];
    }
    const parts = row.title.split(/\s+[—–-]\s+/);
    if (parts.length >= 2) return [parts[0], parts.slice(1).join(' — ')];
    return [row.title, ''];
  }, [row.title, row.company_name, row.companyName]);

  const copyCode = async (e: React.MouseEvent) => {
    e.stopPropagation();
    if (!code) return;
    try {
      await navigator.clipboard.writeText(code);
      setCopied(true);
      toast.success('Code copied');
      setTimeout(() => setCopied(false), 1400);
    } catch {
      toast.error('Could not copy');
    }
  };

  return (
    <tr
      style={{
        borderBottom: '1px solid #f1f5f9',
        transition: 'background 0.1s',
        opacity: isEnded ? 0.72 : 1,
      }}
      onMouseEnter={(e) => (e.currentTarget.style.background = '#fafbfc')}
      onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
    >
      {/* 1. MEETING — icon + company + audit ref subtitle */}
      <td style={{ padding: '14px 12px', verticalAlign: 'middle' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div
            style={{
              flex: 'none',
              width: 40,
              height: 40,
              borderRadius: 10,
              background: isLive
                ? 'linear-gradient(135deg, #22c55e, #15803d)'
                : isEnded
                  ? '#f1f5f9'
                  : 'linear-gradient(135deg, #a855f7, #7c3aed)',
              color: isEnded ? '#94a3b8' : '#fff',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              position: 'relative',
              boxShadow: isLive
                ? '0 4px 10px -3px rgba(34,197,94,0.4)'
                : isEnded
                  ? 'none'
                  : '0 4px 10px -3px rgba(124,58,237,0.35)',
            }}
          >
            <FiVideo size={17} />
            {isLive && (
              <span
                style={{
                  position: 'absolute',
                  top: -2,
                  right: -2,
                  width: 10,
                  height: 10,
                  borderRadius: '50%',
                  background: '#ef4444',
                  border: '2px solid #fff',
                  animation: 'meeting-pulse 1.6s ease-in-out infinite',
                }}
              />
            )}
          </div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div
              style={{
                fontSize: 13.5,
                fontWeight: 700,
                color: '#0f172a',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                marginBottom: 3,
              }}
              title={company || 'Untitled meeting'}
            >
              {company || 'Untitled meeting'}
            </div>
            {ref && (
              <div
                style={{
                  fontSize: 12,
                  color: '#64748b',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                }}
                title={ref}
              >
                {ref}
              </div>
            )}
          </div>
        </div>
      </td>

      {/* 2. CODE — colored monospace + copy + type badge */}
      <td style={{ padding: '14px 12px', verticalAlign: 'middle' }}>
        <div
          style={{
            fontFamily:
              'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
            fontSize: 12,
            fontWeight: 700,
            color: codeColors.text,
            marginBottom: 5,
            display: 'flex',
            alignItems: 'center',
            gap: 6,
          }}
          title={code}
        >
          <span
            style={{
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              flex: 1,
              minWidth: 0,
            }}
          >
            {code || '—'}
          </span>
          {code && (
            <button
              onClick={copyCode}
              title={copied ? 'Copied!' : 'Copy code'}
              style={{
                border: 'none',
                background: 'none',
                color: copied ? '#16a34a' : '#94a3b8',
                cursor: 'pointer',
                padding: 2,
                flex: 'none',
                display: 'inline-flex',
                alignItems: 'center',
              }}
            >
              {copied ? <FiCheck size={12} /> : <FiCopy size={11} />}
            </button>
          )}
        </div>
        <span
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            gap: 4,
            fontSize: 10,
            fontWeight: 700,
            padding: '2px 8px',
            borderRadius: 99,
            background: codeColors.badgeBg,
            color: codeColors.badgeText,
          }}
        >
          <FiVideo size={9} />
          {isLive ? 'Live' : isEnded ? 'Ended' : 'Meeting'}
        </span>
      </td>

      {/* 3. DATE / TIME */}
      <td style={{ padding: '14px 12px', verticalAlign: 'middle' }}>
        {scheduled ? (
          <>
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 8,
                fontSize: 13,
                color: '#0f172a',
                fontWeight: 600,
                marginBottom: 3,
                flexWrap: 'wrap',
              }}
            >
              {dt.date}
              {dt.hint && (
                <span
                  style={{
                    fontSize: 10,
                    fontWeight: 700,
                    padding: '2px 7px',
                    borderRadius: 99,
                    background: dt.hint === 'Today' ? '#dcfce7' : '#f1f5f9',
                    color: dt.hint === 'Today' ? '#166534' : '#475569',
                  }}
                >
                  {dt.hint}
                </span>
              )}
            </div>
            <div
              style={{
                fontSize: 11.5,
                color: '#64748b',
                fontWeight: 600,
                fontFamily:
                  'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
              }}
            >
              {dt.time}
            </div>
          </>
        ) : (
          <span style={{ color: '#94a3b8', fontSize: 12 }}>—</span>
        )}
      </td>

      {/* 4. HOST — avatar + name (+ live participant chip) */}
      <td style={{ padding: '14px 12px', verticalAlign: 'middle' }}>
        {host ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span
              style={{
                width: 28,
                height: 28,
                borderRadius: '50%',
                background: hostColor.bg,
                color: hostColor.text,
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: 10.5,
                fontWeight: 800,
                flex: 'none',
              }}
            >
              {initials(host)}
            </span>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div
                style={{
                  fontSize: 12.5,
                  color: '#334155',
                  fontWeight: 600,
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                }}
                title={host}
              >
                {host}
              </div>
              {isLive && participants > 0 && (
                <span
                  style={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: 3,
                    fontSize: 10.5,
                    color: '#166534',
                    fontWeight: 700,
                    marginTop: 2,
                  }}
                >
                  <FiUsers size={9} /> {participants} joined
                </span>
              )}
            </div>
          </div>
        ) : (
          <span style={{ color: '#94a3b8', fontSize: 12 }}>—</span>
        )}
      </td>

      {/* 5. STATUS */}
      <td style={{ padding: '14px 12px', verticalAlign: 'middle' }}>
        <span
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            gap: 6,
            padding: '3px 10px',
            borderRadius: 99,
            background: statusMeta.bg,
            color: statusMeta.text,
            fontSize: 11.5,
            fontWeight: 700,
          }}
        >
          <span
            style={{
              width: 6,
              height: 6,
              borderRadius: '50%',
              background: statusMeta.dot,
              animation: isLive
                ? 'meeting-pulse 1.6s ease-in-out infinite'
                : 'none',
            }}
          />
          {statusMeta.label}
        </span>
        <style>{`
          @keyframes meeting-pulse {
            0%,100% { transform: scale(1);   opacity: 1; }
            50%     { transform: scale(1.3); opacity: 0.6; }
          }
        `}</style>
      </td>

      {/* 6. ACTIONS */}
      <td style={{ padding: '14px 12px', verticalAlign: 'middle', textAlign: 'right' }}>
        <div
          style={{
            display: 'inline-flex',
            gap: 6,
            alignItems: 'center',
          }}
        >
          {!isEnded && code && (
            <button
              onClick={() => onJoin(code)}
              title="Join meeting"
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: 5,
                padding: '7px 14px',
                borderRadius: 8,
                border: 'none',
                background: isLive
                  ? 'linear-gradient(135deg, #22c55e, #15803d)'
                  : 'linear-gradient(135deg, #7c3aed, #4a0080)',
                color: '#fff',
                fontSize: 12,
                fontWeight: 700,
                cursor: 'pointer',
                whiteSpace: 'nowrap',
                boxShadow: isLive
                  ? '0 4px 10px -3px rgba(34,197,94,0.45)'
                  : '0 4px 10px -3px rgba(124,58,237,0.35)',
              }}
            >
              {isLive ? 'Join Live' : 'Join'} <FiArrowRight size={12} />
            </button>
          )}
          {isEnded && (
            <span
              style={{
                fontSize: 11,
                color: '#94a3b8',
                fontStyle: 'italic',
                padding: '0 8px',
              }}
            >
              Ended
            </span>
          )}
          {!isEnded && (
            <div style={{ position: 'relative' }}>
              <button
                onClick={() => setMenuOpen((v) => !v)}
                onBlur={() => setTimeout(() => setMenuOpen(false), 120)}
                title="More"
                style={{
                  width: 28,
                  height: 28,
                  borderRadius: 7,
                  border: '1px solid #e5e7eb',
                  background: '#fff',
                  color: '#64748b',
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor: 'pointer',
                }}
              >
                <FiMoreVertical size={14} />
              </button>
              {menuOpen && (
                <div
                  style={{
                    position: 'absolute',
                    right: 0,
                    top: 'calc(100% + 4px)',
                    background: '#fff',
                    border: '1px solid #e5e7eb',
                    borderRadius: 8,
                    boxShadow: '0 10px 24px -6px rgba(15,23,42,0.15)',
                    minWidth: 150,
                    overflow: 'hidden',
                    zIndex: 20,
                    textAlign: 'left',
                  }}
                >
                  {onInvite && (
                    <button
                      onMouseDown={() => onInvite(row)}
                      style={menuItem('#334155')}
                    >
                      <FiUserPlus size={13} /> Copy invite
                    </button>
                  )}
                  <button
                    onMouseDown={() => onEnd(row)}
                    style={menuItem('#dc2626')}
                  >
                    <FiXCircle size={13} /> End meeting
                  </button>
                </div>
              )}
            </div>
          )}
        </div>
      </td>
    </tr>
  );
}

function menuItem(color: string): React.CSSProperties {
  return {
    width: '100%',
    display: 'flex',
    alignItems: 'center',
    gap: 8,
    padding: '9px 12px',
    border: 'none',
    background: '#fff',
    color,
    fontSize: 12.5,
    fontWeight: 600,
    cursor: 'pointer',
    textAlign: 'left',
  };
}