'use client';

import React, { useState, useEffect } from 'react';
import AppLayout from '@/components/layout/AppLayout';
import { META_CONFIG } from '@/config/meta';


interface MetricStat {
  label: string;
  value: string;
  change: string;
  isPositive: boolean;
}

interface EventRow {
  name: string;
  total: string;
  browser: string;
  capi: string;
  emq: string;
  status: string;
}

export default function AnalyticsPage() {
  const [dateRange, setDateRange] = useState('Last 7 days');
  const [isLoading, setIsLoading] = useState(true);
  const [stats, setStats] = useState<MetricStat[]>([]);
  const [eventBreakdown, setEventBreakdown] = useState<EventRow[]>([]);

  const fetchAnalytics = async () => {
    setIsLoading(true);
    try {
      const res = await fetch('/api/analytics');
      const data = await res.json();
      if (data.success) {
        setStats(data.stats || []);
        setEventBreakdown(data.eventBreakdown || []);
      }
    } catch (err) {
      console.error('Failed to load analytics:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchAnalytics();
  }, [dateRange]);

  return (
    <AppLayout currentRoute="/analytics">
      <div className="space-y-6">
        {/* Top Controls */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-200/80 pb-4">
          <div>
            <div className="flex items-center gap-2 text-xs font-semibold text-blue-600 uppercase tracking-wider">
              <i className="fa-solid fa-chart-line text-xs" />
              <span>Conversion Intelligence</span>
            </div>
            <h1 className="text-2xl font-bold text-slate-900 tracking-tight mt-1">Pixel Analytics</h1>
            <p className="text-xs text-slate-500">
              Live tracking performance, deduplication rate, and Meta Event Match Quality (EMQ) scores.
            </p>
          </div>

          <div className="flex items-center gap-2">
            <select
              value={dateRange}
              onChange={(e) => setDateRange(e.target.value)}
              className="px-3 py-2 bg-white rounded-xl border border-slate-200 text-xs font-semibold text-slate-700 shadow-2xs focus:outline-none focus:ring-2 focus:ring-blue-500/20"
            >
              <option value="Today">Today</option>
              <option value="Last 7 days">Last 7 days</option>
              <option value="Last 30 days">Last 30 days</option>
              <option value="Lifetime">Lifetime</option>
            </select>

            <button
              onClick={fetchAnalytics}
              disabled={isLoading}
              className="p-2 bg-white rounded-xl border border-slate-200 text-slate-600 hover:bg-slate-50 shadow-2xs transition-colors cursor-pointer"
              title="Refresh Analytics"
            >
              <i className={`fa-solid fa-arrows-rotate text-sm ${isLoading ? 'fa-spin text-blue-600' : ''}`} />
            </button>
          </div>
        </div>

        {/* 4 Metric Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {stats.map((s, idx) => (
            <div key={idx} className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-xs space-y-2 hover:shadow-sm transition-shadow">
              <div className="flex items-center justify-between">
                <span className="text-[11px] font-bold text-slate-400 uppercase tracking-wider">
                  {s.label}
                </span>
                <span className="text-[10px] px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 font-bold border border-emerald-200/60">
                  {s.change}
                </span>
              </div>
              <div className="text-2xl font-extrabold text-slate-900">
                {s.value}
              </div>
            </div>
          ))}
        </div>

        {/* Event Breakdown Table */}
        <div className="bg-white rounded-2xl border border-slate-200/80 shadow-xs overflow-hidden">
          <div className="p-5 border-b border-slate-100 flex items-center justify-between flex-wrap gap-2">
            <div>
              <h3 className="text-sm font-bold text-slate-900">Standard Meta Events Breakdown</h3>
              <p className="text-xs text-slate-400 mt-0.5">Comparing Browser Pixel vs Server-Side Conversions API (CAPI)</p>
            </div>
            <span className="px-2.5 py-1 rounded-full text-[11px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200/60 shadow-2xs">
              Graph API {META_CONFIG.graphVersion} Active
            </span>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs min-w-[640px]">
              <thead className="bg-slate-50/80 border-b border-slate-200/80 text-slate-400 font-bold uppercase text-[10px] tracking-wider">
                <tr>
                  <th className="py-3 px-5">Event Name</th>
                  <th className="py-3 px-5">Total Tracked</th>
                  <th className="py-3 px-5">Browser Pixel</th>
                  <th className="py-3 px-5">Server CAPI</th>
                  <th className="py-3 px-5">EMQ Score</th>
                  <th className="py-3 px-5 text-right">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {eventBreakdown.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="py-12 text-center text-slate-500">
                      <div className="max-w-sm mx-auto space-y-2">
                        <i className="fa-solid fa-chart-line text-slate-300 text-lg block mb-1" />
                        <p className="text-xs font-bold text-slate-800">No Analytics Data Yet</p>
                        <p className="text-[11px] text-slate-400">
                          Events will show up here once storefront visitors trigger PageView, ViewContent, or purchase events.
                        </p>
                      </div>
                    </td>
                  </tr>
                ) : (
                  eventBreakdown.map((row) => (
                    <tr key={row.name} className="hover:bg-slate-50/70 transition-colors">
                      <td className="py-3.5 px-5 font-bold text-slate-900 flex items-center gap-2">
                        <span className={`w-2 h-2 rounded-full ${row.total !== '0' ? 'bg-blue-500' : 'bg-slate-300'}`} />
                        <span>{row.name}</span>
                      </td>
                      <td className="py-3.5 px-5 font-mono font-bold text-slate-900">{row.total}</td>
                      <td className="py-3.5 px-5 font-mono text-slate-600">{row.browser}</td>
                      <td className="py-3.5 px-5 font-mono text-slate-600">{row.capi}</td>
                      <td className="py-3.5 px-5 font-bold text-slate-700">
                        {row.emq !== '—' ? (
                          <span className="px-2 py-0.5 rounded-full bg-indigo-50 border border-indigo-200/60 text-[11px] text-indigo-700">
                            {row.emq} / 10
                          </span>
                        ) : (
                          <span className="text-slate-400 font-normal">—</span>
                        )}
                      </td>
                      <td className="py-3.5 px-5 text-right">
                        {row.status === 'Active' ? (
                          <span className="inline-flex items-center gap-1 text-[11px] font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200/60 shadow-2xs">
                            <i className="fa-solid fa-circle-check text-[11px] text-emerald-500" />
                            Active
                          </span>
                        ) : row.status === 'Browser Only' ? (
                          <span className="inline-flex items-center gap-1 text-[11px] font-bold text-blue-700 bg-blue-50 px-2 py-0.5 rounded-full border border-blue-200/60">
                            Browser
                          </span>
                        ) : (
                          <span className="inline-flex items-center gap-1 text-[11px] font-medium text-slate-500 bg-slate-100 px-2 py-0.5 rounded-full border border-slate-200">
                            No events
                          </span>
                        )}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </AppLayout>
  );
}
