import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { QDRing } from './client360/QDRing';
import { useKanban } from '../../shared/hooks/useKanban';
import styles from './PipelinePillar.module.css';

export default function PipelinePillar() {
  const [viewMode, setViewMode] = useState<'board' | 'list'>('board');
  const { stages, isLoading, isError, refetch } = useKanban();

  useEffect(() => {
    void refetch();
  }, [refetch]);

  return (
    <div className={styles.root}>
      <div className={styles.header}>
        <div>
          <h1 className={styles.title}>Pipeline</h1>
          <p className={styles.subtitle}>Deal Intelligence</p>
        </div>
        <div className={styles.viewToggle}>
          <button
            className={viewMode === 'board' ? styles.toggleActive : styles.toggleBtn}
            onClick={() => setViewMode('board')}
            aria-pressed={viewMode === 'board'}
          >
            Board
          </button>
          <button
            className={viewMode === 'list' ? styles.toggleActive : styles.toggleBtn}
            onClick={() => setViewMode('list')}
            aria-pressed={viewMode === 'list'}
          >
            List
          </button>
        </div>
      </div>

      {isLoading ? (
        <KanbanSkeleton />
      ) : isError ? (
        <PipelineError onRetry={() => void refetch()} />
      ) : viewMode === 'board' ? (
        <KanbanBoard stages={stages} />
      ) : (
        <PipelineList stages={stages} />
      )}
    </div>
  );
}

function PipelineError({ onRetry }: { onRetry: () => void }) {
  return (
    <div className={`${styles.emptyList} glass-card`}>
      <strong>Pipeline data could not be loaded.</strong>
      <span>Retry the CRM read model without refreshing the whole app.</span>
      <button className="btn-ghost" onClick={onRetry}>Retry</button>
    </div>
  );
}

interface Stage {
  id: string;
  label: string;
  emoji: string;
  leads: Lead[];
}

interface Lead {
  id: string;
  name: string;
  location?: string;
  qdScore: number;
  qdDelta?: number;
  lastContactRelative: string;
  lastContactChannel: string;
  isVaultActive?: boolean;
}

function KanbanBoard({ stages }: { stages: Stage[] }) {
  return (
    <div className={styles.board}>
      {stages.map((stage, si) => (
        <motion.div
          key={stage.id}
          className={styles.column}
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: si * 0.06, duration: 0.35, ease: [0.4, 0, 0.2, 1] }}
        >
          <div className={styles.colHeader}>
            <span>{stage.emoji}</span>
            <span className={styles.colLabel}>{stage.label}</span>
            <span className={styles.colCount}>{stage.leads.length}</span>
          </div>

          <div className={styles.cards}>
            {stage.leads.map((lead, li) => (
              <LeadCard key={lead.id} lead={lead} delay={si * 0.06 + li * 0.04} />
            ))}
          </div>
        </motion.div>
      ))}
    </div>
  );
}

function PipelineList({ stages }: { stages: Stage[] }) {
  const navigate = useNavigate();
  const leads = stages.flatMap((stage) =>
    stage.leads.map((lead) => ({
      ...lead,
      stageLabel: stage.label,
      stageEmoji: stage.emoji,
    })),
  );

  return (
    <div className={styles.list} role="table" aria-label="Pipeline lead list">
      <div className={styles.listHeader} role="row">
        <span>Client</span>
        <span>Stage</span>
        <span>QD</span>
        <span>Last contact</span>
      </div>
      {leads.map((lead, index) => (
        <motion.button
          key={lead.id}
          className={styles.listRow}
          onClick={() => navigate(`/pipeline/${lead.id}`)}
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: index * 0.015, duration: 0.22 }}
          aria-label={`View ${lead.name}'s profile`}
        >
          <span className={styles.listIdentity}>
            <span className={styles.avatar}>{lead.name.slice(0, 1)}</span>
            <span>
              <span className={styles.listName}>{lead.name}</span>
              <span className={styles.listMeta}>{lead.location || 'No project captured'}</span>
            </span>
          </span>
          <span className={styles.stagePill}>
            <span>{lead.stageEmoji}</span>
            {lead.stageLabel}
          </span>
          <span className={styles.scoreCell}>{Math.round(lead.qdScore)}</span>
          <span className={styles.listMeta}>
            {lead.lastContactRelative} - {lead.lastContactChannel}
          </span>
        </motion.button>
      ))}
      {leads.length === 0 && <div className={styles.emptyList}>No pipeline leads found.</div>}
    </div>
  );
}

function LeadCard({ lead, delay }: { lead: Lead; delay: number }) {
  const navigate = useNavigate();
  const isVaultLive = lead.isVaultActive;

  return (
    <motion.button
      className={`${styles.card} glass-card`}
      onClick={() => navigate(`/pipeline/${lead.id}`)}
      initial={{ opacity: 0, scale: 0.96 }}
      animate={{
        opacity: 1,
        scale: 1,
        boxShadow: isVaultLive ? '0 0 16px rgba(245,158,11,0.40)' : 'var(--glass-shadow)',
      }}
      transition={{ delay, duration: 0.3 }}
      whileHover={{ scale: 1.02, y: -2 }}
      whileTap={{ scale: 0.99 }}
      aria-label={`View ${lead.name}'s profile`}
    >
      <div className={styles.cardTop}>
        <div className={styles.avatar}>
          <span>{lead.name.slice(0, 1)}</span>
        </div>
        <div className={styles.identity}>
          <span className={styles.cardName}>{lead.name}</span>
          {lead.location && <span className={styles.cardMeta}>{lead.location}</span>}
        </div>
        <div className={styles.qdWrap}>
          <QDRing score={lead.qdScore} size={36} strokeWidth={3} />
        </div>
      </div>

      <div className={styles.cardBottom}>
        <span className={styles.lastContact}>
          {lead.lastContactRelative} - {lead.lastContactChannel}
        </span>
        {isVaultLive && (
          <span className="badge badge-high-intent" style={{ fontSize: '0.65rem' }}>
            <span className="live-dot" style={{ width: 5, height: 5 }} />
            Reviewing
          </span>
        )}
      </div>
    </motion.button>
  );
}

function KanbanSkeleton() {
  return (
    <div className={styles.board}>
      {[0, 1, 2, 3].map((i) => (
        <div key={i} className={styles.column}>
          <div className={`${styles.skeletonHeader} shimmer`} />
          {[0, 1].map((j) => (
            <div key={j} className={`${styles.skeletonCard} shimmer`} />
          ))}
        </div>
      ))}
    </div>
  );
}
