import { useState, useEffect, useRef } from 'react'
import { Link } from 'react-router-dom'
import {
  BarChart3, Clock, Star, CheckCircle2, ArrowUpRight,
  AlertTriangle, Lightbulb, Loader2, Ticket, RotateCcw,
} from 'lucide-react'
import {
  AreaChart, Area, BarChart, Bar,
  XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
} from 'recharts'
import { cn } from '@/lib/utils'
import { flowpilotAnalyticsApi } from '@/api'
import { toast } from '@/lib/toast'
import CoverageHeatmap from '@/components/analytics/CoverageHeatmap'
import FlowQualityTable from '@/components/analytics/FlowQualityTable'
import PsaMetricsPanel from '@/components/analytics/PsaMetricsPanel'
import type {
  FlowPilotDashboard, KnowledgeGapReport, KnowledgeGap,
  CoverageResponse, FlowQualityResponse, EnhancedPsaMetrics,
} from '@/types/flowpilot-analytics'

const PERIOD_OPTIONS = [
  { value: '7d', label: 'Last 7 days' },
  { value: '30d', label: 'Last 30 days' },
  { value: '90d', label: 'Last 90 days' },
]

const TABS = [
  { id: 'overview', label: 'Overview' },
  { id: 'coverage', label: 'Coverage' },
  { id: 'quality', label: 'Flow Quality' },
  { id: 'psa', label: 'PSA' },
] as const

type TabId = typeof TABS[number]['id']

const SEVERITY_STYLES = {
  high: 'bg-rose-500/10 text-rose-500 border-rose-500/20',
  medium: 'bg-amber-400/10 text-amber-400 border-amber-400/20',
  low: 'bg-blue-400/10 text-blue-400 border-blue-400/20',
}

export default function FlowPilotAnalyticsPage() {
  const [period, setPeriod] = useState('30d')
  const [activeTab, setActiveTab] = useState<TabId>('overview')
  const [dashboard, setDashboard] = useState<FlowPilotDashboard | null>(null)
  const [gaps, setGaps] = useState<KnowledgeGapReport | null>(null)
  const [loading, setLoading] = useState(true)

  // Lazy-loaded tab data
  const [coverageData, setCoverageData] = useState<CoverageResponse | null>(null)
  const [coverageLoading, setCoverageLoading] = useState(false)
  const [qualityData, setQualityData] = useState<FlowQualityResponse | null>(null)
  const [qualityLoading, setQualityLoading] = useState(false)
  const [psaData, setPsaData] = useState<EnhancedPsaMetrics | null>(null)
  const [psaLoading, setPsaLoading] = useState(false)

  // Error states per tab
  const [coverageError, setCoverageError] = useState(false)
  const [qualityError, setQualityError] = useState(false)
  const [psaError, setPsaError] = useState(false)
  const [retryKey, setRetryKey] = useState(0)

  // Track which period each tab was loaded for
  const coveragePeriodRef = useRef<string | null>(null)
  const qualityPeriodRef = useRef<string | null>(null)
  const psaPeriodRef = useRef<string | null>(null)

  // Load overview data
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional: syncs derived state from props
    setLoading(true)
    Promise.all([
      flowpilotAnalyticsApi.getDashboard(period),
      flowpilotAnalyticsApi.getKnowledgeGaps(period),
    ])
      .then(([d, g]) => {
        setDashboard(d)
        setGaps(g)
      })
      .catch(() => toast.error('Failed to load analytics'))
      .finally(() => setLoading(false))

    // Reset lazy-loaded data when period changes
    coveragePeriodRef.current = null
    qualityPeriodRef.current = null
    psaPeriodRef.current = null
    setCoverageData(null)
    setQualityData(null)
    setPsaData(null)
    setCoverageLoading(true)
    setQualityLoading(true)
    setPsaLoading(true)
    setCoverageError(false)
    setQualityError(false)
    setPsaError(false)
  }, [period])

  // Lazy-load tab data on tab switch or period change
  useEffect(() => {
    if (activeTab === 'coverage' && coveragePeriodRef.current !== period) {
      // eslint-disable-next-line react-hooks/set-state-in-effect -- fetches data on tab/period change
      setCoverageLoading(true)
      setCoverageError(false)
      flowpilotAnalyticsApi.getCoverage(period)
        .then((data) => {
          setCoverageData(data)
          coveragePeriodRef.current = period
        })
        .catch(() => {
          toast.error('Failed to load coverage data')
          setCoverageError(true)
        })
        .finally(() => setCoverageLoading(false))
    }
    if (activeTab === 'quality' && qualityPeriodRef.current !== period) {
      setQualityLoading(true)
      setQualityError(false)
      flowpilotAnalyticsApi.getFlowQuality(period)
        .then((data) => {
          setQualityData(data)
          qualityPeriodRef.current = period
        })
        .catch(() => {
          toast.error('Failed to load flow quality data')
          setQualityError(true)
        })
        .finally(() => setQualityLoading(false))
    }
    if (activeTab === 'psa' && psaPeriodRef.current !== period) {
      setPsaLoading(true)
      setPsaError(false)
      flowpilotAnalyticsApi.getPsaMetrics(period)
        .then((data) => {
          setPsaData(data)
          psaPeriodRef.current = period
        })
        .catch(() => {
          toast.error('Failed to load PSA metrics')
          setPsaError(true)
        })
        .finally(() => setPsaLoading(false))
    }
  }, [activeTab, period, retryKey])

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <Loader2 size={24} className="animate-spin text-muted-foreground" />
      </div>
    )
  }

  if (!dashboard) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <p className="text-sm text-muted-foreground">Failed to load analytics</p>
      </div>
    )
  }

  const conf = dashboard.confidence_breakdown

  return (
    <div className="container mx-auto px-4 py-6 sm:px-6 sm:py-8 space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          <span title="FlowPilot Analytics">
            <BarChart3 size={24} className="text-foreground" />
          </span>
          <h1 className="text-xl sm:text-2xl font-bold font-heading text-foreground">FlowPilot Analytics</h1>
        </div>
        <div className="flex items-center gap-3">
          <Link
            to="/analytics"
            className="text-sm text-muted-foreground hover:text-foreground transition-colors"
          >
            Team Analytics
          </Link>
          <select
            value={period}
            onChange={(e) => setPeriod(e.target.value)}
            className="rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground focus:outline-hidden focus:ring-1 focus:ring-primary/20 [&>option]:bg-card [&>option]:text-foreground"
          >
            {PERIOD_OPTIONS.map((opt) => (
              <option key={opt.value} value={opt.value}>{opt.label}</option>
            ))}
          </select>
        </div>
      </div>

      {/* Tab bar */}
      <div className="flex gap-1 border-b border-border overflow-x-auto">
        {TABS.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={cn(
              'px-4 py-2 text-sm transition-colors',
              activeTab === tab.id
                ? 'border-b-2 border-primary text-foreground font-medium'
                : 'text-muted-foreground hover:text-foreground'
            )}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab content */}
      {activeTab === 'overview' && (
        <div className="space-y-6">
          {/* Top row — Key metrics */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
            <MetricCard
              icon={BarChart3}
              label="Total Sessions"
              value={dashboard.total_sessions}
              iconColor="#60a5fa"
            />
            <MetricCard
              icon={CheckCircle2}
              label="Resolution Rate"
              value={`${dashboard.resolution_rate}%`}
              iconColor="#34d399"
            />
            <MetricCard
              icon={Clock}
              label="Avg MTTR"
              value={dashboard.mttr_minutes ? `${Math.round(dashboard.mttr_minutes)}m` : '—'}
              iconColor="#60a5fa"
            />
            <MetricCard
              icon={Star}
              label="Avg Rating"
              value={dashboard.avg_rating ? `${dashboard.avg_rating.toFixed(1)}/5` : '—'}
              iconColor="#fbbf24"
            />
            <MetricCard
              icon={Ticket}
              label="PSA Link Rate"
              value={dashboard.psa_metrics ? `${dashboard.psa_metrics.ticket_link_rate}%` : '—'}
              iconColor="#e879f9"
            />
          </div>

          {/* Second row — Charts */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {/* MTTR Trend */}
            <div className="card-flat p-3 sm:p-5">
              <h3 className="font-heading text-sm font-semibold text-foreground mb-4">
                MTTR Trend
              </h3>
              {dashboard.mttr_trend.length > 0 ? (
                <ResponsiveContainer width="100%" height={220}>
                  <AreaChart data={dashboard.mttr_trend}>
                    <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.06)" />
                    <XAxis
                      dataKey="date"
                      tick={{ fill: '#848b9b', fontSize: 10 }}
                      tickFormatter={(d) => new Date(d).toLocaleDateString([], { month: 'short', day: 'numeric' })}
                    />
                    <YAxis
                      tick={{ fill: '#848b9b', fontSize: 10 }}
                      tickFormatter={(v) => `${Math.round(v)}m`}
                    />
                    <Tooltip
                      contentStyle={{ background: 'var(--color-bg-card)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 8, fontSize: 12 }}
                      labelStyle={{ color: '#f0f2f5' }}
                      formatter={(v: number | undefined) => [`${Math.round(v ?? 0)}m`, 'MTTR']}
                    />
                    <Area
                      type="monotone"
                      dataKey="mttr_minutes"
                      stroke="#60a5fa"
                      fill="url(#mttrGradient)"
                      strokeWidth={2}
                    />
                    <defs>
                      <linearGradient id="mttrGradient" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor="#60a5fa" stopOpacity={0.3} />
                        <stop offset="95%" stopColor="#60a5fa" stopOpacity={0} />
                      </linearGradient>
                    </defs>
                  </AreaChart>
                </ResponsiveContainer>
              ) : (
                <div className="flex items-center justify-center h-[220px] text-sm text-muted-foreground">
                  No data for this period
                </div>
              )}
            </div>

            {/* Domain Breakdown */}
            <div className="card-flat p-3 sm:p-5">
              <h3 className="font-heading text-sm font-semibold text-foreground mb-4">
                Sessions by Domain
              </h3>
              {dashboard.sessions_by_domain.length > 0 ? (
                <ResponsiveContainer width="100%" height={220}>
                  <BarChart data={dashboard.sessions_by_domain} layout="vertical">
                    <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.06)" />
                    <XAxis type="number" tick={{ fill: '#848b9b', fontSize: 10 }} />
                    <YAxis
                      type="category"
                      dataKey="domain"
                      tick={{ fill: '#848b9b', fontSize: 10 }}
                      width={100}
                    />
                    <Tooltip
                      contentStyle={{ background: 'var(--color-bg-card)', border: '1px solid rgba(255,255,255,0.06)', borderRadius: 8, fontSize: 12 }}
                      labelStyle={{ color: '#f0f2f5' }}
                    />
                    <Bar dataKey="resolved" name="Resolved" fill="#34d399" radius={[0, 4, 4, 0]} />
                    <Bar dataKey="escalated" name="Escalated" fill="#fbbf24" radius={[0, 4, 4, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              ) : (
                <div className="flex items-center justify-center h-[220px] text-sm text-muted-foreground">
                  No domain data
                </div>
              )}
            </div>
          </div>

          {/* Third row — Confidence + Knowledge Coverage */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {/* Confidence Breakdown */}
            <div className="card-flat p-3 sm:p-5">
              <h3 className="font-heading text-sm font-semibold text-foreground mb-4">
                Confidence Tiers
              </h3>
              <div className="space-y-3">
                <ConfidenceTierRow
                  label="Guided"
                  count={conf.guided_sessions}
                  rate={conf.guided_resolution_rate}
                  color="#34d399"
                  total={conf.guided_sessions + conf.exploring_sessions + conf.discovery_sessions}
                />
                <ConfidenceTierRow
                  label="Exploring"
                  count={conf.exploring_sessions}
                  rate={conf.exploring_resolution_rate}
                  color="#fbbf24"
                  total={conf.guided_sessions + conf.exploring_sessions + conf.discovery_sessions}
                />
                <ConfidenceTierRow
                  label="Discovery"
                  count={conf.discovery_sessions}
                  rate={conf.discovery_resolution_rate}
                  color="#f87171"
                  total={conf.guided_sessions + conf.exploring_sessions + conf.discovery_sessions}
                />
              </div>
            </div>

            {/* Knowledge Coverage */}
            <div className="card-flat p-3 sm:p-5">
              <h3 className="font-heading text-sm font-semibold text-foreground mb-4">
                Knowledge Coverage
              </h3>
              <div className="grid grid-cols-2 gap-3 mb-4">
                <div className="rounded-lg bg-card/50 p-3">
                  <p className="text-xs text-muted-foreground">Total Flows</p>
                  <p className="text-lg font-semibold text-foreground">{dashboard.knowledge_coverage.total_flows}</p>
                </div>
                <div className="rounded-lg bg-card/50 p-3">
                  <p className="text-xs text-muted-foreground">AI-Generated</p>
                  <p className="text-lg font-semibold text-accent-text">{dashboard.knowledge_coverage.ai_generated_flows}</p>
                </div>
                <div className="rounded-lg bg-card/50 p-3">
                  <p className="text-xs text-muted-foreground">Pending Review</p>
                  <p className="text-lg font-semibold text-amber-400">{dashboard.knowledge_coverage.total_proposals_pending}</p>
                </div>
                <div className="rounded-lg bg-card/50 p-3">
                  <p className="text-xs text-muted-foreground">Approved This Period</p>
                  <p className="text-lg font-semibold text-emerald-400">{dashboard.knowledge_coverage.proposals_approved_this_period}</p>
                </div>
              </div>
              {dashboard.knowledge_coverage.total_proposals_pending > 0 && (
                <Link
                  to="/review-queue"
                  className="flex items-center gap-2 text-xs text-primary hover:underline"
                >
                  <ArrowUpRight size={12} />
                  Review {dashboard.knowledge_coverage.total_proposals_pending} pending proposals
                </Link>
              )}
            </div>
          </div>

          {/* Fourth row — Knowledge Gaps */}
          {gaps && gaps.gaps.length > 0 ? (
            <div className="space-y-3">
              <div className="flex items-center gap-2 px-1">
                <AlertTriangle size={14} className="text-amber-400" />
                <h3 className="font-heading text-sm font-semibold text-foreground">
                  Knowledge Gaps ({gaps.gaps.length})
                </h3>
              </div>
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
                {gaps.gaps.map((gap, i) => (
                  <GapCard key={i} gap={gap} />
                ))}
              </div>
            </div>
          ) : gaps && (
            <div className="card-flat p-4 flex items-center gap-3">
              <CheckCircle2 size={20} className="text-emerald-400 shrink-0" />
              <div>
                <p className="text-sm text-foreground">No knowledge gaps detected</p>
                <p className="text-xs text-muted-foreground">Your flow coverage looks healthy for this period.</p>
              </div>
            </div>
          )}
        </div>
      )}

      {activeTab === 'coverage' && (
        <div>
          {coverageError ? (
            <ErrorRetry label="coverage data" onRetry={() => { setCoverageError(false); coveragePeriodRef.current = null; setRetryKey((k) => k + 1) }} />
          ) : coverageLoading ? (
            <div className="flex items-center justify-center min-h-[200px]">
              <Loader2 size={20} className="animate-spin text-muted-foreground" />
            </div>
          ) : coverageData ? (
            <CoverageHeatmap data={coverageData} />
          ) : null}
        </div>
      )}

      {activeTab === 'quality' && (
        <div>
          {qualityError ? (
            <ErrorRetry label="flow quality data" onRetry={() => { setQualityError(false); qualityPeriodRef.current = null; setRetryKey((k) => k + 1) }} />
          ) : qualityLoading ? (
            <div className="flex items-center justify-center min-h-[200px]">
              <Loader2 size={20} className="animate-spin text-muted-foreground" />
            </div>
          ) : qualityData ? (
            <FlowQualityTable data={qualityData} />
          ) : null}
        </div>
      )}

      {activeTab === 'psa' && (
        <div>
          {psaError ? (
            <ErrorRetry label="PSA metrics" onRetry={() => { setPsaError(false); psaPeriodRef.current = null; setRetryKey((k) => k + 1) }} />
          ) : psaLoading ? (
            <div className="flex items-center justify-center min-h-[200px]">
              <Loader2 size={20} className="animate-spin text-muted-foreground" />
            </div>
          ) : psaData ? (
            <PsaMetricsPanel data={psaData} />
          ) : null}
        </div>
      )}
    </div>
  )
}

// ── Sub-components ──

function MetricCard({
  icon: Icon,
  label,
  value,
  iconColor,
}: {
  icon: typeof BarChart3
  label: string
  value: string | number
  iconColor: string
}) {
  return (
    <div className="card-flat p-3 sm:p-4">
      <div className="flex items-center gap-3">
        <span
          className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg"
          style={{ background: `${iconColor}15` }}
        >
          <Icon size={16} style={{ color: iconColor }} />
        </span>
        <div>
          <p className="font-sans text-xs text-[0.5625rem] uppercase tracking-wider text-text-muted">{label}</p>
          <p className="text-lg font-semibold text-foreground">{value}</p>
        </div>
      </div>
    </div>
  )
}

function ConfidenceTierRow({
  label,
  count,
  rate,
  color,
  total,
}: {
  label: string
  count: number
  rate: number
  color: string
  total: number
}) {
  const pct = total > 0 ? (count / total) * 100 : 0
  return (
    <div className="space-y-1">
      <div className="flex items-center justify-between text-xs">
        <span className="text-foreground font-medium">{label}</span>
        <span className="text-muted-foreground">
          {count} sessions · {rate.toFixed(1)}% resolved
        </span>
      </div>
      <div className="h-2 rounded-full bg-card/80 overflow-hidden">
        <div
          className="h-full rounded-full transition-all"
          style={{ width: `${pct}%`, background: color }}
        />
      </div>
    </div>
  )
}

function ErrorRetry({ label, onRetry }: { label: string; onRetry: () => void }) {
  return (
    <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
      <AlertTriangle size={24} className="mb-2 text-amber-400" />
      <p className="text-sm mb-3">Failed to load {label}</p>
      <button
        onClick={onRetry}
        className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-lg bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] text-foreground hover:border-[rgba(255,255,255,0.12)] transition-colors"
      >
        <RotateCcw size={12} />
        Retry
      </button>
    </div>
  )
}

function GapCard({ gap }: { gap: KnowledgeGap }) {
  const severityStyle = SEVERITY_STYLES[gap.severity as keyof typeof SEVERITY_STYLES] ?? SEVERITY_STYLES.low
  return (
    <div className="card-flat p-4 space-y-2">
      <div className="flex items-start justify-between gap-2">
        <p className="text-sm font-semibold text-foreground">{gap.title}</p>
        <span className={`shrink-0 rounded-md border px-1.5 py-0.5 font-sans text-xs text-[0.5625rem] uppercase tracking-wider ${severityStyle}`}>
          {gap.severity}
        </span>
      </div>
      <p className="text-xs text-muted-foreground">{gap.description}</p>
      <div className="flex items-start gap-1.5 pt-1">
        <Lightbulb size={12} className="text-primary shrink-0 mt-0.5" />
        <p className="text-xs text-primary">{gap.suggested_action}</p>
      </div>
    </div>
  )
}
