import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import { QDRing } from './QDRing';
import { ConversationsTab } from './tabs/Conversations';
import { IntelligenceTab } from './tabs/Intelligence';
import { PropertiesTab } from './tabs/Properties';
import { TasksTab } from './tabs/Tasks';
import { useClient360 } from '../../../shared/hooks/useClient360';
import styles from './Client360.module.css';

/**
 * Client360
 * The unified client entity. The most important screen in Velocity-OS.
 * Accessible at /pipeline/:personId — slides in with depth choreography.
 *
 * Four tabs only: Conversations | Intelligence | Properties | Tasks
 * Header: glassmorphic, always visible with QD ring, pipeline stage, last contact.
 */

type Tab = 'conversations' | 'intelligence' | 'properties' | 'tasks';

const TABS: { id: Tab; label: string }[] = [
  { id: 'conversations', label: 'Conversations' },
  { id: 'intelligence',  label: 'Intelligence'  },
  { id: 'properties',    label: 'Properties'    },
  { id: 'tasks',         label: 'Tasks'         },
];

export default function Client360() {
  const { personId } = useParams<{ personId: string }>();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [activeTab, setActiveTab] = useState<Tab>('conversations');

  const { client, isLoading, error } = useClient360(personId!);
  const backToPipeline = () => {
    void queryClient.invalidateQueries({ queryKey: ['kanban'] });
    navigate('/pipeline', { replace: true });
  };

  if (isLoading) return <Client360Skeleton />;
  if (error || !client) return <Client360Error onBack={backToPipeline} />;

  const qdColor =
    client.qdScore >= 70 ? 'var(--color-green)' :
    client.qdScore >= 40 ? 'var(--color-amber)' :
                           'var(--color-red)';

  const intentLabel =
    client.qdScore >= 70 ? 'HIGH INTENT' :
    client.qdScore >= 40 ? 'MODERATE'    :
                           'LOW INTENT';

  return (
    <div className={styles.root}>
      {/* Back button */}
      <button
        className={styles.backBtn}
        onClick={backToPipeline}
        aria-label="Back to Pipeline"
      >
        ← Pipeline
      </button>

      {/* ── Glassmorphic Header ─────────────────────────────── */}
      <div className={`${styles.header} glass-heavy`}>
        <div className={styles.headerTop}>
          {/* Avatar + Identity */}
          <div className={styles.identity}>
            <div className={styles.avatar}>
              {client.avatarUrl
                ? <img src={client.avatarUrl} alt={client.name} />
                : <span>{client.name.slice(0, 1)}</span>
              }
            </div>
            <div className={styles.nameBlock}>
              <h1 className={styles.name}>{client.name}</h1>
              <p className={styles.meta}>
                {client.location}
                {client.primaryPhone && ` · ${client.primaryPhone}`}
              </p>
            </div>
          </div>

          {/* Intent badge */}
          <span className={`badge badge-high-intent ${styles.intentBadge}`}
            style={{ borderColor: qdColor, color: qdColor }}>
            <span className="live-dot" style={{ background: qdColor }} />
            {intentLabel}
          </span>
        </div>

        {/* ── Three KPI chips ──────────────────────────────── */}
        <div className={styles.kpiRow}>
          {/* QD Score chip */}
          <div className={`${styles.kpiChip} glass`}>
            <span className={styles.kpiLabel}>QD SCORE</span>
            <div className={styles.qdWrap}>
              <QDRing score={client.qdScore} size={48} color={qdColor} />
              <div>
                <span className={styles.qdValue}
                  style={{ color: qdColor }}>{client.qdScore}</span>
                {client.qdDelta !== 0 && (
                  <span className={styles.qdDelta}
                    style={{ color: client.qdDelta > 0 ? 'var(--color-green)' : 'var(--color-red)' }}>
                    {client.qdDelta > 0 ? '+' : ''}{client.qdDelta} this week
                  </span>
                )}
              </div>
            </div>
          </div>

          {/* Pipeline Stage chip */}
          <div className={`${styles.kpiChip} glass`}>
            <span className={styles.kpiLabel}>PIPELINE STAGE</span>
            <span className={styles.kpiValue}>
              {client.stageEmoji} {client.stageName}
            </span>
          </div>

          {/* Last Contact chip */}
          <div className={`${styles.kpiChip} glass`}>
            <span className={styles.kpiLabel}>LAST CONTACT</span>
            <span className={styles.kpiValue}>{client.lastContactRelative}</span>
            <span className={styles.kpiSub}>via {client.lastContactChannel}</span>
          </div>
        </div>

        {/* ── Primary action bar ───────────────────────────── */}
        <div className={styles.actionBar}>
          <ActionButton
            icon="💬"
            label={client.lastContactChannel === 'WhatsApp' ? 'WhatsApp' : 'Message'}
            onClick={() => {/* open inline compose */}}
            primary
          />
          <ActionButton icon="📞" label="Call"     onClick={() => window.open(`tel:${client.primaryPhone}`)} />
          <ActionButton icon="📅" label="Schedule" onClick={() => {/* open task modal */}} />
          <ActionButton icon="⋯" label="More"      onClick={() => {/* slide-up sheet */}} />
        </div>
      </div>

      {/* ── Tab Navigation ──────────────────────────────────── */}
      <div className={styles.tabNav} role="tablist">
        {TABS.map(({ id, label }) => (
          <button
            key={id}
            role="tab"
            aria-selected={activeTab === id}
            className={`${styles.tabBtn} ${activeTab === id ? styles.tabActive : ''}`}
            onClick={() => setActiveTab(id)}
          >
            {label}
            {activeTab === id && (
              <motion.div
                layoutId="tab-underline"
                className={styles.tabUnderline}
                transition={{ type: 'spring', stiffness: 500, damping: 40 }}
              />
            )}
          </button>
        ))}
      </div>

      {/* ── Tab Content ─────────────────────────────────────── */}
      <div className={styles.tabContent}>
        <AnimatePresence mode="wait" initial={false}>
          <motion.div
            key={activeTab}
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -4 }}
            transition={{ duration: 0.2, ease: [0.4, 0, 0.2, 1] }}
          >
            {activeTab === 'conversations' && <ConversationsTab personId={personId!} />}
            {activeTab === 'intelligence'  && <IntelligenceTab  client={client} />}
            {activeTab === 'properties'    && <PropertiesTab    personId={personId!} />}
            {activeTab === 'tasks'         && <TasksTab         personId={personId!} />}
          </motion.div>
        </AnimatePresence>
      </div>
    </div>
  );
}

// ── Sub-components ───────────────────────────────────────────
function ActionButton({
  icon, label, onClick, primary = false,
}: { icon: string; label: string; onClick: () => void; primary?: boolean }) {
  return (
    <button
      className={primary ? 'btn-primary' : 'btn-ghost'}
      onClick={onClick}
      aria-label={label}
    >
      <span>{icon}</span> {label}
    </button>
  );
}

function Client360Skeleton() {
  return (
    <div className={styles.root}>
      <div className={`${styles.header} glass-heavy shimmer`} style={{ minHeight: 220 }} />
      <div style={{ padding: 'var(--space-6)', display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        {[1,2,3].map(i => (
          <div key={i} className="glass shimmer" style={{ height: 80, borderRadius: 'var(--radius-lg)' }} />
        ))}
      </div>
    </div>
  );
}

function Client360Error({ onBack }: { onBack: () => void }) {
  return (
    <div className={styles.root} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 'var(--space-4)', padding: 'var(--space-16)' }}>
      <p style={{ color: 'var(--color-text-secondary)' }}>Could not load client profile.</p>
      <button className="btn-ghost" onClick={onBack}>← Back to Pipeline</button>
    </div>
  );
}
