'use client';

import { useState } from 'react';
import {
  ChevronDown,
  ChevronUp,
  Phone,
  MessageSquare,
  TrendingUp,
  Clock,
  Workflow,
  Plug,
  GitBranch,
  CalendarDays,
} from 'lucide-react';
import { cn, formatPhone, relativeTime } from '@/lib/utils';

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface BotData {
  id: string;
  name: string;
  category: string;
  active: boolean;
  locked: boolean;
  favorited: boolean;
  twilioNumber: string | null;
  routeId: string | null;
  sourceIds: string[];
  sourceNames: string[];
  modifiedAt: string;
  messageCount: number;
  conversionPct: number | null;
  lastActive: string | null;
  publishedVersions: number;
  totalVersions: number;
}

interface BotCardProps {
  bot: BotData;
  index: number;
  onToggle?: (id: string, active: boolean) => void;
}

// Gradient colors rotate based on card index
const GRADIENT_COLORS = [
  'from-blue-500 to-blue-600',
  'from-purple-500 to-purple-600',
  'from-cyan-400 to-cyan-500',
  'from-green-400 to-green-500',
];

// Mini sparkline bars — purely visual performance indicator
function Sparkline({ values }: { values: number[] }) {
  const max = Math.max(...values, 1);
  return (
    <div className="flex items-end gap-[3px] h-8">
      {values.map((v, i) => (
        <div
          key={i}
          className="w-[6px] rounded-sm bg-cyan-400/70 transition-all"
          style={{ height: `${(v / max) * 100}%`, minHeight: 2 }}
        />
      ))}
    </div>
  );
}

// ---------------------------------------------------------------------------
// BotCard
// ---------------------------------------------------------------------------
export function BotCard({ bot, index, onToggle }: BotCardProps) {
  const [expanded, setExpanded] = useState(false);
  const gradient = GRADIENT_COLORS[index % GRADIENT_COLORS.length];

  // Fake sparkline data seeded from message count so it's stable
  const spark = Array.from({ length: 12 }, (_, i) => {
    const seed = (bot.messageCount * (i + 1) * 7 + i * 31) % 100;
    return seed;
  });

  return (
    <div
      className={cn(
        'card group relative overflow-hidden transition-all duration-300',
        'hover:border-slate-500/60 hover:shadow-lg hover:shadow-cyan-900/10',
        !bot.active && 'opacity-50 grayscale-[30%]'
      )}
    >
      {/* Gradient top border */}
      <div
        className={cn(
          'absolute top-0 left-0 right-0 h-[3px] bg-gradient-to-r',
          gradient
        )}
      />

      {/* Header */}
      <div className="p-5 pb-3 flex items-start justify-between">
        <div className="min-w-0 flex-1">
          <h3 className="text-white font-semibold text-base truncate">
            {bot.name}
          </h3>
          <span className="text-xs text-slate-400 capitalize">{bot.category}</span>
        </div>

        <div className="flex items-center gap-3 ml-3 flex-shrink-0">
          {/* Active toggle */}
          <button
            onClick={(e) => {
              e.stopPropagation();
              onToggle?.(bot.id, !bot.active);
            }}
            className={cn(
              'relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-cyan-400/40',
              bot.active ? 'bg-green-500' : 'bg-slate-600'
            )}
            aria-label={bot.active ? 'Deactivate bot' : 'Activate bot'}
          >
            <span
              className={cn(
                'inline-block h-3.5 w-3.5 rounded-full bg-white shadow transition-transform',
                bot.active ? 'translate-x-[18px]' : 'translate-x-[3px]'
              )}
            />
          </button>

          {/* Expand chevron */}
          <button
            onClick={() => setExpanded((p) => !p)}
            className="text-slate-400 hover:text-white transition-colors p-0.5"
            aria-label={expanded ? 'Collapse' : 'Expand'}
          >
            {expanded ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
          </button>
        </div>
      </div>

      {/* Field rows */}
      <div className="px-5 pb-4 space-y-2.5 text-sm">
        {/* Twilio Number */}
        <div className="flex items-center gap-2 text-slate-300">
          <Phone size={14} className="text-slate-500 flex-shrink-0" />
          <span className="text-slate-400 w-20 flex-shrink-0">Twilio #</span>
          <span className={cn('truncate', bot.twilioNumber ? 'text-slate-200' : 'text-slate-500 italic')}>
            {bot.twilioNumber ? formatPhone(bot.twilioNumber) : 'Unassigned'}
          </span>
        </div>

        {/* Messages */}
        <div className="flex items-center gap-2 text-slate-300">
          <MessageSquare size={14} className="text-slate-500 flex-shrink-0" />
          <span className="text-slate-400 w-20 flex-shrink-0">Messages</span>
          <span className="num text-slate-200">{bot.messageCount.toLocaleString()}</span>
        </div>

        {/* Conversion */}
        <div className="flex items-center gap-2 text-slate-300">
          <TrendingUp size={14} className="text-slate-500 flex-shrink-0" />
          <span className="text-slate-400 w-20 flex-shrink-0">Conv. %</span>
          <span
            className={cn(
              'num',
              bot.conversionPct !== null
                ? bot.conversionPct >= 30
                  ? 'text-green-400'
                  : bot.conversionPct >= 15
                  ? 'text-yellow-400'
                  : 'text-slate-300'
                : 'text-slate-500'
            )}
          >
            {bot.conversionPct !== null ? `${bot.conversionPct.toFixed(1)}%` : '—'}
          </span>
        </div>

        {/* Last Active */}
        <div className="flex items-center gap-2 text-slate-300">
          <Clock size={14} className="text-slate-500 flex-shrink-0" />
          <span className="text-slate-400 w-20 flex-shrink-0">Active</span>
          <span className="text-slate-200">
            {bot.lastActive ? relativeTime(bot.lastActive) : '—'}
          </span>
        </div>

        {/* Published Versions */}
        <div className="flex items-center gap-2 text-slate-300">
          <GitBranch size={14} className="text-slate-500 flex-shrink-0" />
          <span className="text-slate-400 w-20 flex-shrink-0">Versions</span>
          <span className="text-slate-200">
            {bot.publishedVersions > 0 ? (
              <><span className="text-green-400 font-medium">{bot.publishedVersions}</span> published / {bot.totalVersions} total</>
            ) : (
              <span className="text-slate-500">{bot.totalVersions} draft{bot.totalVersions !== 1 ? 's' : ''}</span>
            )}
          </span>
        </div>

        {/* Modified Date */}
        <div className="flex items-center gap-2 text-slate-300">
          <CalendarDays size={14} className="text-slate-500 flex-shrink-0" />
          <span className="text-slate-400 w-20 flex-shrink-0">Modified</span>
          <span className="text-slate-200">
            {bot.modifiedAt ? relativeTime(bot.modifiedAt) : '—'}
          </span>
        </div>
      </div>

      {/* Expanded area */}
      {expanded && (
        <div className="border-t border-slate-700/50 px-5 py-4 space-y-4 animate-in slide-in-from-top-2 duration-200">
          {/* Connected Sources */}
          <div>
            <div className="flex items-center gap-1.5 text-xs font-medium text-slate-400 mb-2">
              <Plug size={12} />
              Connected Sources
            </div>
            {bot.sourceNames.length > 0 ? (
              <div className="flex flex-wrap gap-1.5">
                {bot.sourceNames.map((name) => (
                  <span
                    key={name}
                    className="badge bg-slate-700/60 text-slate-300 border-slate-600/50"
                  >
                    {name}
                  </span>
                ))}
              </div>
            ) : (
              <span className="text-xs text-slate-500 italic">No sources connected</span>
            )}
          </div>

          {/* Mini Performance Sparkline */}
          <div>
            <div className="text-xs font-medium text-slate-400 mb-2">
              Message Volume (12-period)
            </div>
            <Sparkline values={spark} />
          </div>

          {/* Edit Flow button */}
          <button
            className={cn(
              'w-full flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm font-medium',
              'bg-cyan-500/10 text-cyan-400 border border-cyan-500/20',
              'hover:bg-cyan-500/20 transition-colors'
            )}
          >
            <Workflow size={14} />
            Edit Flow
          </button>
        </div>
      )}
    </div>
  );
}
