import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { useData } from '../hooks/useData';

interface Overview {
  total_sessions: number;
  unique_users: number;
  date_range: { start: string; end: string };
  days_of_data: number;
  sources: Record<string, number>;
  estimated_cost_usd: number;
  session_duration?: {
    active_context?: string;
  };
}

export default function Methodology() {
  const [open, setOpen] = useState(false);
  const { data: overview } = useData<Overview>('/data/overview.json', {
    total_sessions: 0, unique_users: 0, date_range: { start: '', end: '' },
    days_of_data: 0, sources: {}, estimated_cost_usd: 0,
  });

  const startDate = overview.date_range.start
    ? new Date(overview.date_range.start).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
    : '—';
  const endDate = overview.date_range.end
    ? new Date(overview.date_range.end).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
    : '—';

  const assumptions = [
    { label: 'Date range analyzed', value: `${startDate} to ${endDate} (${overview.days_of_data?.toFixed(1) ?? '—'} days)` },
    { label: 'Total sessions', value: `${overview.total_sessions} across ${overview.unique_users} developers` },
    { label: 'Organization filter', value: "Only sessions from 'pratilipi%' orgs are included" },
    { label: 'Data source', value: 'Local PostgreSQL database snapshot — may not reflect all historical sessions' },
    { label: 'CLI tools analyzed', value: Object.entries(overview.sources || {}).map(([k, v]) => `${k.replace('_', ' ')} (${v})`).join(', ') || '—' },
    { label: 'Session duration methodology', value: 'Sum of assistant response times (user msg timestamp to assistant reply timestamp). Gaps > 30 min are discarded as idle/abandoned. This is NOT wall-clock time.' },
    { label: '"Active time" definition', value: 'Cumulative time where inter-message gaps are < 30 minutes. Everything else is classified as idle.' },
    { label: '"Idle time" definition', value: 'Any gap > 30 minutes between consecutive messages in a session. These periods are excluded from active time calculations.' },
    { label: 'Cost estimation model', value: 'Based on Anthropic API pricing: Claude 3.5 Sonnet at $3/1M input tokens, $15/1M output tokens. Cached tokens at $0.30/1M. Codex CLI pricing: GPT-4o at $2.50/1M input, $10/1M output.' },
    { label: 'Cost estimation caveats', value: 'Actual billing depends on model variant, batch pricing, enterprise agreements, and token counting differences. These are estimates based on public list prices.' },
    { label: 'Intent classification', value: 'Rule-based keyword matching on user messages. Categories: feature, bugfix, refactor, explore, test, deploy, config. Not mutually exclusive.' },
    { label: 'Developer personas', value: 'Computed from explore-to-edit ratio, user message count, and tool call patterns. Categories: Explorer, Delegator, Collaborator, Builder, Balanced.' },
    { label: 'Data limitations', value: `This analysis covers only ${overview.days_of_data?.toFixed(1) ?? '—'} days of data. Trends and annualized projections should be interpreted with caution. Commit detection is excluded as unreliable.` },
  ];

  return (
    <section className="px-8 max-w-7xl mx-auto py-10">
      <button
        onClick={() => setOpen(!open)}
        className="w-full flex items-center justify-between bg-surface-1 border border-border-dim rounded-xl px-6 py-4 hover:bg-surface-2/50 transition-colors"
      >
        <div className="text-left">
          <h3 className="text-sm font-semibold text-text-1">Methodology & Assumptions</h3>
          <p className="text-xs text-text-3 mt-0.5">
            How every metric in this dashboard was calculated. {assumptions.length} disclosed assumptions.
          </p>
        </div>
        {open ? <ChevronUp size={16} className="text-text-3" /> : <ChevronDown size={16} className="text-text-3" />}
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.3 }}
            className="overflow-hidden"
          >
            <div className="mt-3 bg-surface-1 border border-border-dim rounded-xl p-6">
              <div className="grid grid-cols-1 gap-4">
                {assumptions.map((a, i) => (
                  <div key={i} className="flex gap-4 text-xs">
                    <div className="w-48 shrink-0 font-semibold text-text-2 uppercase tracking-wider text-[10px] pt-0.5">
                      {a.label}
                    </div>
                    <div className="text-text-2 leading-relaxed">{a.value}</div>
                  </div>
                ))}
              </div>

              <div className="mt-6 pt-4 border-t border-border-dim">
                <p className="text-[10px] text-text-3 leading-relaxed">
                  This dashboard was generated from AI CLI trace data captured by qc-trace.
                  All metrics are computed from raw session, message, and tool call data.
                  No metrics are self-reported by developers.
                  The analysis period is {overview.days_of_data?.toFixed(1)} days — annualized projections
                  assume consistent usage patterns and should be treated as directional, not precise.
                </p>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </section>
  );
}
