'use client';
import React, { useEffect, useState } from 'react';
import api from '@/lib/api';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell
} from 'recharts';

interface QRCode {
  id: string;
  name: string;
  short_url_id: string;
}

interface AnalyticsData {
  totalScans: number;
  osBreakdown: { os: string; count: string }[];
  deviceBreakdown: { device_type: string; count: string }[];
  timeline: { date: string; count: string }[];
}

const COLORS = ['#4f46e5', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'];

export default function AnalyticsPage() {
  const [qrs, setQrs] = useState<QRCode[]>([]);
  const [selectedQrId, setSelectedQrId] = useState<string>('');
  const [analytics, setAnalytics] = useState<AnalyticsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [loadingAnalytics, setLoadingAnalytics] = useState(false);

  // Fetch QRs on mount
  useEffect(() => {
    const fetchQRs = async () => {
      try {
        const res = await api.get('/qr');
        const qrList = res.data.qr_codes || [];
        setQrs(qrList);
        if (qrList.length > 0) {
          setSelectedQrId(qrList[0].id);
        }
      } catch (err) {
        console.error("Failed to fetch QRs", err);
      } finally {
        setLoading(false);
      }
    };
    fetchQRs();
  }, []);

  // Fetch analytics when selectedQrId changes
  useEffect(() => {
    if (!selectedQrId) return;
    
    const fetchAnalytics = async () => {
      setLoadingAnalytics(true);
      try {
        const res = await api.get(`/analytics/${selectedQrId}`);
        setAnalytics(res.data);
      } catch (err) {
        console.error("Failed to fetch analytics", err);
        setAnalytics(null);
      } finally {
        setLoadingAnalytics(false);
      }
    };
    fetchAnalytics();
  }, [selectedQrId]);

  if (loading) {
    return <div className="p-8 text-center text-gray-500">Loading your data...</div>;
  }

  if (qrs.length === 0) {
    return (
      <div className="p-8 max-w-4xl mx-auto font-sans h-full flex flex-col items-center justify-center">
        <h1 className="text-2xl font-bold text-gray-900 mb-2">No data yet</h1>
        <p className="text-gray-500 mb-6">Create a dynamic QR code first to see analytics.</p>
      </div>
    );
  }

  return (
    <div className="p-8 max-w-6xl mx-auto font-sans">
      
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 bg-white p-6 rounded-2xl shadow-sm border border-gray-200 gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-gray-900 tracking-tight">Analytics & Insights</h1>
          <p className="text-gray-500 mt-1">Deep dive into your QR scan metrics.</p>
        </div>
        
        {/* QR Selector */}
        <div className="w-full md:w-64">
           <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-2">Select QR Code</label>
           <select 
             value={selectedQrId} 
             onChange={(e) => setSelectedQrId(e.target.value)}
             className="w-full bg-gray-50 border border-gray-300 text-gray-900 rounded-xl px-4 py-2.5 font-semibold focus:ring-2 focus:ring-indigo-500 focus:border-transparent outline-none transition-all shadow-sm"
           >
             {qrs.map(qr => (
               <option key={qr.id} value={qr.id}>{qr.name} (/l/{qr.short_url_id})</option>
             ))}
           </select>
        </div>
      </div>

      {loadingAnalytics ? (
         <div className="py-20 text-center text-indigo-500 font-bold animate-pulse">Crunching numbers...</div>
      ) : !analytics ? (
         <div className="py-20 text-center text-red-500 font-bold">Failed to load analytics data.</div>
      ) : (
        <div className="space-y-6">
          
          {/* Top Metric Cards */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
             <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
                <h3 className="text-sm font-bold text-gray-500 uppercase tracking-wider mb-2">Total Scans</h3>
                <div className="text-5xl font-black text-indigo-600">{analytics.totalScans.toLocaleString()}</div>
             </div>
             
             {/* Adding placeholders for conversion rate / unique scanners since backend doesn't track unique yet */}
             <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 opacity-50">
                <h3 className="text-sm font-bold text-gray-500 uppercase tracking-wider mb-2">Unique Scanners</h3>
                <div className="text-5xl font-black text-gray-900">--</div>
                <p className="text-xs text-gray-400 mt-2">Available in Pro</p>
             </div>
             
             <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 opacity-50">
                <h3 className="text-sm font-bold text-gray-500 uppercase tracking-wider mb-2">Top Location</h3>
                <div className="text-3xl font-black text-gray-900 mt-2">Unknown</div>
                <p className="text-xs text-gray-400 mt-2">Available in Pro</p>
             </div>
          </div>

          {/* Timeline Chart */}
          <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
             <h3 className="text-lg font-bold text-gray-900 mb-6">Scans Over Time (Last 7 Days)</h3>
             <div className="h-72 w-full">
                {analytics.timeline.length > 0 ? (
                  <ResponsiveContainer width="100%" height="100%">
                    <LineChart data={analytics.timeline}>
                      <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#e5e7eb" />
                      <XAxis dataKey="date" tick={{fontSize: 12, fill: '#6b7280'}} axisLine={false} tickLine={false} tickFormatter={(val) => new Date(val).toLocaleDateString(undefined, {month: 'short', day: 'numeric'})} />
                      <YAxis tick={{fontSize: 12, fill: '#6b7280'}} axisLine={false} tickLine={false} />
                      <Tooltip contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }} />
                      <Line type="monotone" dataKey="count" stroke="#4f46e5" strokeWidth={4} dot={{r: 4, fill: '#4f46e5', strokeWidth: 2, stroke: '#fff'}} activeDot={{r: 6}} />
                    </LineChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="h-full flex items-center justify-center text-gray-400">No scan data for the past 7 days.</div>
                )}
             </div>
          </div>

          {/* Breakdown Charts */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
             
             {/* Device Types */}
             <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
                <h3 className="text-lg font-bold text-gray-900 mb-6">Device Types</h3>
                <div className="h-64 flex items-center justify-center">
                   {analytics.deviceBreakdown.length > 0 ? (
                     <ResponsiveContainer width="100%" height="100%">
                       <PieChart>
                         <Pie
                           data={analytics.deviceBreakdown}
                           cx="50%"
                           cy="50%"
                           innerRadius={60}
                           outerRadius={80}
                           paddingAngle={5}
                           dataKey="count"
                           nameKey="device_type"
                         >
                           {analytics.deviceBreakdown.map((entry, index) => (
                             <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                           ))}
                         </Pie>
                         <Tooltip contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }} />
                       </PieChart>
                     </ResponsiveContainer>
                   ) : (
                     <span className="text-gray-400">No device data</span>
                   )}
                </div>
                {/* Legend */}
                <div className="flex justify-center gap-4 flex-wrap mt-2">
                   {analytics.deviceBreakdown.map((entry, index) => (
                     <div key={index} className="flex items-center gap-2">
                        <span className="w-3 h-3 rounded-full" style={{backgroundColor: COLORS[index % COLORS.length]}}></span>
                        <span className="text-sm font-medium text-gray-700 capitalize">{entry.device_type} ({entry.count})</span>
                     </div>
                   ))}
                </div>
             </div>

             {/* Operating Systems */}
             <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
                <h3 className="text-lg font-bold text-gray-900 mb-6">Operating Systems</h3>
                <div className="h-64 flex items-center justify-center">
                   {analytics.osBreakdown.length > 0 ? (
                     <ResponsiveContainer width="100%" height="100%">
                       <PieChart>
                         <Pie
                           data={analytics.osBreakdown}
                           cx="50%"
                           cy="50%"
                           innerRadius={60}
                           outerRadius={80}
                           paddingAngle={5}
                           dataKey="count"
                           nameKey="os"
                         >
                           {analytics.osBreakdown.map((entry, index) => (
                             <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                           ))}
                         </Pie>
                         <Tooltip contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }} />
                       </PieChart>
                     </ResponsiveContainer>
                   ) : (
                     <span className="text-gray-400">No OS data</span>
                   )}
                </div>
                {/* Legend */}
                <div className="flex justify-center gap-4 flex-wrap mt-2">
                   {analytics.osBreakdown.map((entry, index) => (
                     <div key={index} className="flex items-center gap-2">
                        <span className="w-3 h-3 rounded-full" style={{backgroundColor: COLORS[index % COLORS.length]}}></span>
                        <span className="text-sm font-medium text-gray-700 capitalize">{entry.os || 'Unknown'} ({entry.count})</span>
                     </div>
                   ))}
                </div>
             </div>

          </div>

        </div>
      )}
    </div>
  );
}
