import { ArrowRight, ArrowDown } from 'lucide-react'
import {
  ComposedChart, Area, Bar,
  XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
} from 'recharts'
import type { EnhancedPsaMetrics, PsaFunnel } from '@/types/flowpilot-analytics'

interface PsaMetricsPanelProps {
  data: EnhancedPsaMetrics
}

function funnelPct(from: number, to: number): string {
  if (from === 0) return '0%'
  return `${Math.round((to / from) * 100)}%`
}

export default function PsaMetricsPanel({ data }: PsaMetricsPanelProps) {
  const hasActivity = data.total_time_entries > 0 || data.push_funnel.total_sessions > 0 || data.daily_trend.length > 0

  if (!hasActivity) {
    return (
      <div className="card-flat p-3 sm:p-5">
        <div className="flex items-center justify-center min-h-[200px]">
          <p className="text-sm text-muted-foreground">
            No PSA activity data for this period. Link sessions to PSA tickets to see metrics.
          </p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Row 1 — Metric cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="card-flat p-4">
          <p className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-text-muted">Time Entries</p>
          <p className="text-accent-text font-heading text-2xl mt-1">{data.total_time_entries}</p>
          <p className="text-xs text-muted-foreground mt-1">logged to PSA</p>
        </div>
        <div className="card-flat p-4">
          <p className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-text-muted">Hours Logged</p>
          <p className="text-accent-text font-heading text-2xl mt-1">{data.total_hours_logged.toFixed(1)}</p>
          <p className="text-xs text-muted-foreground mt-1">total hours tracked</p>
        </div>
        <div className="card-flat p-4">
          <p className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-text-muted">Avg Hours/Session</p>
          <p className="text-accent-text font-heading text-2xl mt-1">{data.avg_hours_per_session.toFixed(2)}</p>
          <p className="text-xs text-muted-foreground mt-1">per resolved session</p>
        </div>
      </div>

      {/* Row 2 — Push Success Funnel */}
      <FunnelCard funnel={data.push_funnel} />

      {/* Row 3 — Daily Trend Chart */}
      {data.daily_trend.length > 0 && (
        <div className="card-flat p-3 sm:p-5">
          <h3 className="font-heading text-sm font-semibold text-foreground mb-4">
            PSA Activity Trend
          </h3>
          <ResponsiveContainer width="100%" height={250}>
            <ComposedChart data={data.daily_trend}>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.06)" />
              <XAxis
                dataKey="date"
                tick={{ fill: '#8891a0', fontSize: 10 }}
                tickFormatter={(d) => new Date(d).toLocaleDateString([], { month: 'short', day: 'numeric' })}
              />
              <YAxis
                yAxisId="entries"
                orientation="left"
                tick={{ fill: '#8891a0', fontSize: 10 }}
                label={{ value: 'Entries', angle: -90, position: 'insideLeft', style: { fill: '#8891a0', fontSize: 10 } }}
              />
              <YAxis
                yAxisId="hours"
                orientation="right"
                tick={{ fill: '#8891a0', fontSize: 10 }}
                label={{ value: 'Hours', angle: 90, position: 'insideRight', style: { fill: '#8891a0', fontSize: 10 } }}
              />
              <Tooltip
                contentStyle={{
                  background: '#18191f',
                  border: '1px solid rgba(255,255,255,0.06)',
                  borderRadius: 8,
                  fontSize: 12,
                }}
                labelStyle={{ color: '#f8fafc' }}
                formatter={((value: number | undefined, name: string | undefined) => [
                  name === 'hours' ? `${(value ?? 0).toFixed(1)}h` : (value ?? 0),
                  name === 'hours' ? 'Hours' : 'Entries',
                ]) as never}
              />
              <Bar
                yAxisId="entries"
                dataKey="entries"
                fill="rgba(96,165,250,0.3)"
                radius={[4, 4, 0, 0]}
              />
              <Area
                yAxisId="hours"
                type="monotone"
                dataKey="hours"
                stroke="#60a5fa"
                fill="url(#psaHoursGradient)"
                strokeWidth={2}
              />
              <defs>
                <linearGradient id="psaHoursGradient" 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>
            </ComposedChart>
          </ResponsiveContainer>
        </div>
      )}
    </div>
  )
}

function FunnelCard({ funnel }: { funnel: PsaFunnel }) {
  const steps = [
    { label: 'Sessions', count: funnel.total_sessions },
    { label: 'Linked', count: funnel.linked_to_ticket },
    { label: 'Doc Pushed', count: funnel.doc_pushed },
    { label: 'Time Entry', count: funnel.time_entry_logged },
  ]

  return (
    <div className="card-flat p-3 sm:p-5">
      <h3 className="font-heading text-sm font-semibold text-foreground mb-4">
        Documentation Push Funnel
      </h3>

      {/* Desktop: horizontal */}
      <div className="hidden sm:flex items-center gap-2">
        {steps.map((step, i) => (
          <div key={step.label} className="flex items-center gap-2 flex-1">
            <div className="bg-primary/5 border border-primary/20 rounded-lg p-3 text-center flex-1">
              <p className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground">
                {step.label}
              </p>
              <p className="text-lg font-heading text-foreground">{step.count}</p>
            </div>
            {i < steps.length - 1 && (
              <div className="flex flex-col items-center shrink-0 px-1">
                <ArrowRight size={14} className="text-muted-foreground" />
                <span className="text-[0.625rem] text-muted-foreground font-sans text-xs">
                  {funnelPct(steps[i].count, steps[i + 1].count)}
                </span>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* Mobile: vertical */}
      <div className="flex sm:hidden flex-col items-center gap-2">
        {steps.map((step, i) => (
          <div key={step.label} className="flex flex-col items-center gap-2 w-full">
            <div className="bg-primary/5 border border-primary/20 rounded-lg p-3 text-center w-full">
              <p className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground">
                {step.label}
              </p>
              <p className="text-lg font-heading text-foreground">{step.count}</p>
            </div>
            {i < steps.length - 1 && (
              <div className="flex items-center gap-1">
                <ArrowDown size={14} className="text-muted-foreground" />
                <span className="text-[0.625rem] text-muted-foreground font-sans text-xs">
                  {funnelPct(steps[i].count, steps[i + 1].count)}
                </span>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  )
}
