import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { analyticsApi } from '../api/client';
import { AlertCircle, Database } from 'lucide-react';
import { PieChart, Pie, Cell, BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Legend } from 'recharts';

const COLORS = ['#6366f1', '#0ea5e9', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#14b8a6'];

export function AnalyticsPage() {
  const [days, setDays] = useState(30);

  const { data, isLoading, isError } = useQuery({
    queryKey: ['analytics', days],
    queryFn: () => analyticsApi.getAnalytics(days),
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="space-y-6">
        <div>
          <h2 className="text-xl font-semibold text-text-primary border-b-2 border-primary/30 pb-2 mb-2">
            Analytics Dashboard
          </h2>
        </div>
        <div className="bg-gradient-to-br from-primary/10 to-secondary/5 border border-primary/20 rounded-xl p-6">
          <div className="flex items-center gap-3 text-warning mb-2">
            <Database size={24} />
            <span className="font-semibold">Database Not Connected</span>
          </div>
          <p className="text-text-secondary">
            Set <code className="bg-bg-card px-2 py-1 rounded">USE_DATABASE=true</code> in your .env file to enable analytics tracking.
          </p>
        </div>
        <div className="flex items-center gap-2 bg-secondary/10 border border-secondary/20 text-secondary rounded-xl px-4 py-3">
          <AlertCircle size={18} />
          <span>Analytics features require storing analysis results in PostgreSQL for historical tracking.</span>
        </div>
      </div>
    );
  }

  if (!data || (data.total_messages === 0 && data.by_company.length === 0)) {
    return (
      <div className="space-y-6">
        <div>
          <h2 className="text-xl font-semibold text-text-primary border-b-2 border-primary/30 pb-2 mb-2">
            Analytics Dashboard
          </h2>
          <p className="text-text-secondary">Track historical analysis data and view insights.</p>
        </div>
        <div className="flex items-center gap-2 bg-secondary/10 border border-secondary/20 text-secondary rounded-xl px-4 py-3">
          <AlertCircle size={18} />
          <span>No analytics data available yet. Run some analyses first!</span>
        </div>
      </div>
    );
  }

  const companyData = data.by_company.map((c) => ({
    name: (c.company_name || 'Unknown').toUpperCase(),
    value: c.count,
  }));

  const typeData = data.by_type.map((t) => ({
    name: t.analysis_type || 'Unknown',
    count: t.count,
  }));

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h2 className="text-xl font-semibold text-text-primary border-b-2 border-primary/30 pb-2 mb-2">
            Analytics Dashboard
          </h2>
          <p className="text-text-secondary">Track historical analysis data and view insights.</p>
        </div>

        {/* Time Range Selector */}
        <select
          value={days}
          onChange={(e) => setDays(Number(e.target.value))}
          className="bg-bg-card/80 border border-primary/30 rounded-xl px-4 py-2 text-text-primary focus:outline-none focus:border-primary"
        >
          <option value={7}>Last 7 days</option>
          <option value={14}>Last 14 days</option>
          <option value={30}>Last 30 days</option>
          <option value={90}>Last 90 days</option>
        </select>
      </div>

      {/* Summary Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <MetricCard label="Total Analyses" value={data.total_messages} />
        <MetricCard label="Companies Analyzed" value={data.by_company.length} />
        <MetricCard label="Analysis Types" value={data.by_type.length} />
      </div>

      {/* Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Pie Chart - Distribution by Company */}
        {companyData.length > 0 && (
          <div className="bg-bg-card/60 border border-primary/15 rounded-2xl p-6">
            <h3 className="text-lg font-semibold text-text-primary mb-4">Distribution by Company</h3>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={companyData}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={100}
                  paddingAngle={2}
                  dataKey="value"
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  labelLine={false}
                >
                  {companyData.map((_, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip
                  contentStyle={{
                    backgroundColor: '#1e293b',
                    border: '1px solid rgba(99, 102, 241, 0.3)',
                    borderRadius: '8px',
                  }}
                />
                <Legend />
              </PieChart>
            </ResponsiveContainer>
          </div>
        )}

        {/* Bar Chart - Analysis Types */}
        {typeData.length > 0 && (
          <div className="bg-bg-card/60 border border-primary/15 rounded-2xl p-6">
            <h3 className="text-lg font-semibold text-text-primary mb-4">Analysis Types</h3>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={typeData}>
                <XAxis dataKey="name" stroke="#94a3b8" fontSize={12} />
                <YAxis stroke="#94a3b8" fontSize={12} />
                <Tooltip
                  contentStyle={{
                    backgroundColor: '#1e293b',
                    border: '1px solid rgba(99, 102, 241, 0.3)',
                    borderRadius: '8px',
                  }}
                  labelStyle={{ color: '#f8fafc' }}
                />
                <Bar dataKey="count" fill="#6366f1" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        )}
      </div>
    </div>
  );
}

function MetricCard({ label, value }: { label: string; value: number }) {
  return (
    <div className="bg-gradient-to-br from-primary/10 to-secondary/10 border border-primary/20 rounded-xl p-5 text-center">
      <div className="text-3xl font-bold bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
        {value}
      </div>
      <div className="text-sm text-text-secondary uppercase tracking-wide mt-1">{label}</div>
    </div>
  );
}
