'use client';
import { useState } from 'react';
import { motion } from 'framer-motion';
import { MessageSquare, Link, Trash2, BookOpen, Clock, RotateCcw, MoreVertical, RefreshCw, Mail } from 'lucide-react';
import ProgressBar from './ProgressBar';
import { getSportEmoji, getTimeAgo, formatWordCount } from '@/utils/analytics';
import type { Client } from '@/utils/api';

interface Props {
  client: Client;
  index: number;
  onInterview: () => void;
  onCopyLink: () => void;
  onDelete: () => void;
  onViewBook: () => void;
  onReset: () => void;
  onRegenerateLink: () => void;
}

const PART_PROGRESS = [
  { label: 'Roots',    color: '#6366f1', threshold: 25  },
  { label: 'Journey',  color: '#a855f7', threshold: 50  },
  { label: 'Glory',    color: '#f59e0b', threshold: 75  },
  { label: 'Legacy',   color: '#10b981', threshold: 100 },
];

export default function ClientCard({ client, index, onInterview, onCopyLink, onDelete, onViewBook, onReset, onRegenerateLink }: Props) {
  const [showMenu, setShowMenu] = useState(false);

  const statusClass = client.status === 'active' ? 'badge-active'
    : client.status === 'completed' ? 'badge-completed' : 'badge-pending';

  // Figure out which part we're in based on progress
  const currentPart = PART_PROGRESS.find(p => client.progress < p.threshold) || PART_PROGRESS[3];

  // Extract chapter count from messages if available
  const messages = Array.isArray(client.messages) ? client.messages : [];
  const completedChapters = messages.filter((m: any) => m.type === 'chapter_end' && m.chapterComplete).length;

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: index * 0.05, duration: 0.35 }}
      className="card p-5 flex flex-col gap-3 relative">

      {/* Header */}
      <div className="flex items-start justify-between gap-2">
        <div className="flex items-center gap-3 min-w-0">
          <div className="w-11 h-11 rounded-xl flex items-center justify-center text-2xl flex-shrink-0"
            style={{ background: 'linear-gradient(135deg, rgba(99,102,241,0.12), rgba(168,85,247,0.12))' }}>
            {getSportEmoji(client.sport)}
          </div>
          <div className="min-w-0">
            <h3 className="font-bold text-sm truncate" style={{ color: 'var(--text-primary)' }}>{client.name}</h3>
            <p className="text-xs truncate" style={{ color: 'var(--text-secondary)' }}>{client.bookTitle}</p>
            <p className="text-xs mt-0.5" style={{ color: 'var(--text-secondary)' }}>{client.email}</p>
          </div>
        </div>
        <div className="flex items-center gap-1.5 flex-shrink-0">
          <span className={statusClass}>{client.status}</span>
          {/* More menu */}
          <div className="relative">
            <button onClick={() => setShowMenu(!showMenu)}
              className="btn-ghost p-1.5 rounded-lg" title="More options">
              <MoreVertical className="w-3.5 h-3.5" />
            </button>
            {showMenu && (
              <div className="absolute right-0 top-full mt-1 w-44 rounded-xl shadow-xl border z-50 overflow-hidden"
                style={{ background: 'var(--bg-card)', borderColor: 'var(--border)' }}
                onMouseLeave={() => setShowMenu(false)}>
                <button onClick={() => { onRegenerateLink(); setShowMenu(false); }}
                  className="w-full px-3 py-2.5 text-left text-xs flex items-center gap-2 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors"
                  style={{ color: 'var(--text-primary)' }}>
                  <RefreshCw className="w-3.5 h-3.5 text-indigo-500" /> Regenerate Link
                </button>
                <button onClick={() => { window.open(`mailto:${client.email}?subject=Your Interview Link&body=Hi ${client.name}, here is your interview link: ${window.location.origin}/interview/link/${client.uniqueLink}`); setShowMenu(false); }}
                  className="w-full px-3 py-2.5 text-left text-xs flex items-center gap-2 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors"
                  style={{ color: 'var(--text-primary)' }}>
                  <Mail className="w-3.5 h-3.5 text-purple-500" /> Email Link
                </button>
                <div className="border-t" style={{ borderColor: 'var(--border)' }} />
                <button onClick={() => { onReset(); setShowMenu(false); }}
                  className="w-full px-3 py-2.5 text-left text-xs flex items-center gap-2 hover:bg-amber-50 dark:hover:bg-amber-900/20 transition-colors text-amber-600">
                  <RotateCcw className="w-3.5 h-3.5" /> Reset Interview
                </button>
                <button onClick={() => { onDelete(); setShowMenu(false); }}
                  className="w-full px-3 py-2.5 text-left text-xs flex items-center gap-2 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors text-red-500">
                  <Trash2 className="w-3.5 h-3.5" /> Delete Client
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Chapter progress */}
      <div>
        <div className="flex justify-between text-xs mb-1.5">
          <span style={{ color: 'var(--text-secondary)' }}>
            {completedChapters > 0 ? `${completedChapters}/12 chapters` : `${client.progress}% complete`}
          </span>
          <span style={{ color: currentPart.color, fontWeight: 600 }}>
            {client.progress > 0 ? currentPart.label : 'Not started'}
          </span>
        </div>
        <ProgressBar value={client.progress} />
        {/* Part indicators */}
        <div className="flex mt-1.5 gap-0.5">
          {PART_PROGRESS.map(p => (
            <div key={p.label} className="flex-1 h-1 rounded-full transition-all"
              style={{ background: client.progress >= p.threshold ? p.color : `${p.color}25` }} />
          ))}
        </div>
      </div>

      {/* Stats row */}
      <div className="flex items-center gap-3 text-xs" style={{ color: 'var(--text-secondary)' }}>
        <span className="flex items-center gap-1">
          <Clock className="w-3 h-3" />{getTimeAgo(client.lastActive)}
        </span>
        <span>•</span>
        <span className="capitalize">{client.sport}</span>
        <span>•</span>
        <span>{formatWordCount(client.wordCount)} words</span>
      </div>

      {/* Interview link preview */}
      <div className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg text-xs truncate"
        style={{ background: 'var(--bg-secondary)', border: '1px solid var(--border)' }}>
        <Link className="w-3 h-3 flex-shrink-0" style={{ color: '#6366f1' }} />
        <span className="truncate" style={{ color: 'var(--text-secondary)' }}>
          /interview/link/{client.uniqueLink}
        </span>
        <button onClick={onCopyLink} className="flex-shrink-0 text-indigo-500 hover:text-indigo-400 font-medium ml-auto">
          Copy
        </button>
      </div>

      {/* Primary actions */}
      <div className="flex gap-2 pt-1 border-t" style={{ borderColor: 'var(--border)' }}>
        <button onClick={onInterview}
          className="btn-primary flex-1 py-2 text-xs flex items-center justify-center gap-1.5">
          <MessageSquare className="w-3.5 h-3.5" />
          {client.status === 'pending' ? 'Start Interview' : 'Continue'}
        </button>
        {client.bookDraft && (
          <button onClick={onViewBook}
            className="btn-secondary py-2 px-3 text-xs flex items-center gap-1.5"
            title="View book">
            <BookOpen className="w-3.5 h-3.5" />
            <span className="hidden sm:inline">Book</span>
          </button>
        )}
      </div>
    </motion.div>
  );
}
