'use client';

import { useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Calendar, ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
import StatCardSparkline from '@/components/analytics/stat-card-sparkline';
import MessagesChart from '@/components/analytics/messages-chart';
import BotsBarChart from '@/components/analytics/bots-bar-chart';
import OutcomeDonut from '@/components/analytics/outcome-donut';
import BotLeaderboard from '@/components/analytics/bot-leaderboard';

const tabs = [
  { label: 'Dashboard', href: '/' },
  { label: 'Conversations', href: '/conversations' },
  { label: 'Bots', href: '/bots' },
  { label: 'Contacts', href: '/contacts' },
  { label: 'Settings', href: '/settings' },
];

const dateRanges = [
  { label: 'Last 7 Days', days: 7 },
  { label: 'Last 14 Days', days: 14 },
  { label: 'Last 30 Days', days: 30 },
  { label: 'Last 90 Days', days: 90 },
];

function getDateRangeLabel(days: number) {
  const end = new Date();
  const start = new Date();
  start.setDate(end.getDate() - days);

  const fmt = (d: Date) =>
    d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });

  return `${fmt(start)} - ${fmt(end)}`;
}

export default function AnalyticsPage() {
  const pathname = usePathname();
  const [dateRange, setDateRange] = useState(30);
  const [showDatePicker, setShowDatePicker] = useState(false);

  const selectedRange = dateRanges.find((r) => r.days === dateRange) || dateRanges[2];

  return (
    <div className="p-6 lg:p-8 space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white tracking-tight">
            CloseBot SMS{' '}
            <span className="text-slate-500 font-normal">|</span>{' '}
            <span className="bg-gradient-to-r from-cyan-400 to-blue-400 bg-clip-text text-transparent">
              Analytics
            </span>
          </h1>
          <p className="text-sm text-slate-500 mt-1">
            Performance metrics and conversation insights
          </p>
        </div>

        {/* Date Range Picker */}
        <div className="relative">
          <button
            onClick={() => setShowDatePicker(!showDatePicker)}
            className={cn(
              'flex items-center gap-2 rounded-lg border px-4 py-2.5 text-sm transition-all',
              showDatePicker
                ? 'border-cyan-500/50 bg-cyan-500/5 text-white'
                : 'border-slate-700/50 bg-slate-800/50 text-slate-300 hover:border-slate-600/50 hover:text-white'
            )}
          >
            <Calendar className="h-4 w-4 text-slate-400" />
            <span className="font-medium">
              Last {dateRange} Days
            </span>
            <span className="text-xs text-slate-500 hidden sm:inline">
              ({getDateRangeLabel(dateRange)})
            </span>
            <ChevronDown
              className={cn(
                'h-3.5 w-3.5 text-slate-500 transition-transform',
                showDatePicker && 'rotate-180'
              )}
            />
          </button>

          {showDatePicker && (
            <>
              <div
                className="fixed inset-0 z-10"
                onClick={() => setShowDatePicker(false)}
              />
              <div className="absolute right-0 top-full mt-2 z-20 w-56 rounded-lg border border-slate-700/60 bg-[#1a2332] py-1 shadow-xl">
                {dateRanges.map((range) => (
                  <button
                    key={range.days}
                    onClick={() => {
                      setDateRange(range.days);
                      setShowDatePicker(false);
                    }}
                    className={cn(
                      'w-full px-4 py-2.5 text-left text-sm transition-colors',
                      dateRange === range.days
                        ? 'bg-cyan-500/10 text-cyan-400'
                        : 'text-slate-300 hover:bg-slate-800/50 hover:text-white'
                    )}
                  >
                    <span className="font-medium">{range.label}</span>
                    <span className="block text-[10px] text-slate-500 mt-0.5">
                      {getDateRangeLabel(range.days)}
                    </span>
                  </button>
                ))}
              </div>
            </>
          )}
        </div>
      </div>

      {/* Tab Nav */}
      <div className="flex items-center gap-1 border-b border-slate-700/30 -mx-6 lg:-mx-8 px-6 lg:px-8">
        {tabs.map((tab) => {
          const isActive =
            tab.href === '/analytics'
              ? true
              : tab.href === '/'
              ? pathname === '/'
              : pathname.startsWith(tab.href);

          // Analytics tab is always active on this page
          const active = tab.label === 'Dashboard' ? false : tab.href === '/analytics' ? true : isActive;

          return (
            <Link
              key={tab.href}
              href={tab.href === '/analytics' ? '/analytics' : tab.href}
              className={cn(
                'relative px-4 py-3 text-sm font-medium transition-colors',
                active
                  ? 'text-cyan-400'
                  : 'text-slate-500 hover:text-slate-300'
              )}
            >
              {tab.label}
              {active && (
                <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-cyan-400 rounded-full" />
              )}
            </Link>
          );
        })}
      </div>

      {/* Stat Cards Row */}
      <StatCardSparkline />

      {/* Messages Over Time — full width */}
      <MessagesChart />

      {/* Two-column: Bots Bar + Outcome Donut */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <BotsBarChart />
        <OutcomeDonut />
      </div>

      {/* Bot Leaderboard — full width */}
      <BotLeaderboard />
    </div>
  );
}
