'use client';

import { useState, useEffect } from 'react';
import { visitorApi, VisitorStatsOverview, TopPage, TopReferrer, ChartData, RealtimeStats } from '@/lib/api';

// Country code to name mapping
const countryNames: Record<string, string> = {
  MN: 'Mongolia',
  RU: 'Russia',
  KR: 'Korea',
  US: 'United States',
  CN: 'China',
  JP: 'Japan',
  DE: 'Germany',
  FR: 'France',
  GB: 'United Kingdom',
  AU: 'Australia',
  unknown: 'Unknown',
  LO: 'Local',
};

// Simple bar chart component
const SimpleBarChart = ({ data, color = 'bg-primary-500', height = 120 }: {
  data: ChartData | null;
  color?: string;
  height?: number;
}) => {
  if (!data || data.values.length === 0) {
    return <div className="text-gray-400 text-center py-4">No data</div>;
  }

  const maxValue = Math.max(...data.values, 1);

  return (
    <div className="flex items-end gap-1" style={{ height }}>
      {data.values.map((value, index) => (
        <div key={index} className="flex-1 flex flex-col items-center group relative">
          <div className="hidden group-hover:block absolute -top-8 bg-gray-800 text-white text-xs px-2 py-1 rounded z-10 whitespace-nowrap">
            {data.labels[index]}: {value}
          </div>
          <div
            className={`w-full ${color} rounded-t transition-all hover:opacity-80`}
            style={{ height: `${(value / maxValue) * 100}%`, minHeight: value > 0 ? '4px' : '0' }}
          />
        </div>
      ))}
    </div>
  );
};

// Breakdown card component
const BreakdownCard = ({ title, data, icon, nameMap }: {
  title: string;
  data: Record<string, number>;
  icon: string;
  nameMap?: Record<string, string>;
}) => {
  const total = Object.values(data).reduce((a, b) => a + b, 0);
  const sortedEntries = Object.entries(data).sort((a, b) => b[1] - a[1]).slice(0, 5);

  const colors = ['bg-blue-500', 'bg-green-500', 'bg-purple-500', 'bg-amber-500', 'bg-red-500'];

  if (total === 0) {
    return (
      <div className="bg-white rounded-xl shadow-sm p-5">
        <div className="flex items-center gap-2 mb-4">
          <span className="text-xl">{icon}</span>
          <h3 className="font-semibold text-gray-800">{title}</h3>
        </div>
        <div className="text-gray-400 text-center py-4">No data</div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-xl shadow-sm p-5">
      <div className="flex items-center gap-2 mb-4">
        <span className="text-xl">{icon}</span>
        <h3 className="font-semibold text-gray-800">{title}</h3>
      </div>
      <div className="space-y-3">
        {sortedEntries.map(([key, value], index) => {
          const displayName = nameMap ? (nameMap[key] || key) : key;
          return (
            <div key={key} className="flex items-center gap-3">
              <div className={`w-3 h-3 rounded-full ${colors[index] || 'bg-gray-400'}`} />
              <div className="flex-1">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-700">{displayName || 'Unknown'}</span>
                  <span className="text-gray-500">{value} ({((value / total) * 100).toFixed(1)}%)</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-1.5 mt-1">
                  <div
                    className={`h-1.5 rounded-full ${colors[index] || 'bg-gray-400'}`}
                    style={{ width: `${(value / total) * 100}%` }}
                  />
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default function VisitorStatsPage() {
  const [overview, setOverview] = useState<VisitorStatsOverview | null>(null);
  const [visitsChart, setVisitsChart] = useState<ChartData | null>(null);
  const [uniqueChart, setUniqueChart] = useState<ChartData | null>(null);
  const [topPages, setTopPages] = useState<TopPage[]>([]);
  const [topReferrers, setTopReferrers] = useState<TopReferrer[]>([]);
  const [realtime, setRealtime] = useState<RealtimeStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [days, setDays] = useState(30);

  useEffect(() => {
    loadData();
  }, [days]);

  // Realtime refresh every 30 seconds
  useEffect(() => {
    const interval = setInterval(loadRealtime, 30000);
    return () => clearInterval(interval);
  }, []);

  const loadRealtime = async () => {
    try {
      const realtimeData = await visitorApi.getRealtime(5);
      setRealtime(realtimeData);
    } catch (error) {
      console.error('Failed to load realtime stats:', error);
    }
  };

  const loadData = async () => {
    try {
      setLoading(true);
      const [overviewData, visitsData, uniqueData, pagesData, referrersData, realtimeData] = await Promise.all([
        visitorApi.getOverview(days),
        visitorApi.getVisitsChart(days),
        visitorApi.getUniqueVisitorsChart(days),
        visitorApi.getTopPages(days),
        visitorApi.getTopReferrers(days),
        visitorApi.getRealtime(5),
      ]);
      setOverview(overviewData);
      setVisitsChart(visitsData);
      setUniqueChart(uniqueData);
      setTopPages(pagesData);
      setTopReferrers(referrersData);
      setRealtime(realtimeData);
    } catch (error) {
      console.error('Failed to load visitor stats:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatNumber = (num: number) => new Intl.NumberFormat('ko-KR').format(num);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-800">Visitor Statistics</h1>
        <div className="flex items-center gap-4">
          <select
            value={days}
            onChange={(e) => setDays(Number(e.target.value))}
            className="px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
          >
            <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>
          <button
            onClick={loadData}
            className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm transition-colors"
          >
            Refresh
          </button>
        </div>
      </div>

      {/* Realtime Stats */}
      {realtime && (
        <div className="bg-gradient-to-r from-green-500 to-emerald-600 rounded-xl shadow-sm p-5 text-white">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-3 h-3 bg-white rounded-full animate-pulse"></div>
              <span className="font-semibold">Real-time Visitors</span>
            </div>
            <span className="text-3xl font-bold">{realtime.active_visitors}</span>
          </div>
          <p className="text-green-100 text-sm mt-1">Active in the last {realtime.minutes} minutes</p>
          {realtime.recent_pages.length > 0 && (
            <div className="mt-3 pt-3 border-t border-green-400/30">
              <p className="text-green-100 text-xs mb-2">Active Pages:</p>
              <div className="flex flex-wrap gap-2">
                {realtime.recent_pages.slice(0, 3).map((page, i) => (
                  <span key={i} className="bg-white/20 px-2 py-1 rounded text-xs">
                    {page.path} ({page.views})
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Overview Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl shadow-sm p-5">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-gray-500 text-sm">Total Page Views</p>
              <p className="text-2xl font-bold text-gray-800 mt-1">
                {formatNumber(overview?.total_visits || 0)}
              </p>
            </div>
            <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center text-2xl">
              <svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
              </svg>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm p-5">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-gray-500 text-sm">Unique Visitors</p>
              <p className="text-2xl font-bold text-gray-800 mt-1">
                {formatNumber(overview?.unique_visitors || 0)}
              </p>
            </div>
            <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center text-2xl">
              <svg className="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
              </svg>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm p-5">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-gray-500 text-sm">Pages per Visit</p>
              <p className="text-2xl font-bold text-gray-800 mt-1">
                {overview && overview.unique_visitors > 0
                  ? (overview.total_visits / overview.unique_visitors).toFixed(1)
                  : '0'}
              </p>
            </div>
            <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center text-2xl">
              <svg className="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm p-5">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-gray-500 text-sm">Mobile Visitors</p>
              <p className="text-2xl font-bold text-gray-800 mt-1">
                {overview?.device_breakdown?.mobile && overview.total_visits > 0
                  ? `${((overview.device_breakdown.mobile / overview.total_visits) * 100).toFixed(0)}%`
                  : '0%'}
              </p>
            </div>
            <div className="w-12 h-12 bg-amber-100 rounded-lg flex items-center justify-center text-2xl">
              <svg className="w-6 h-6 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      {/* Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="bg-white rounded-xl shadow-sm p-5">
          <h3 className="font-semibold text-gray-800 mb-4">Page Views</h3>
          <SimpleBarChart data={visitsChart} color="bg-blue-500" height={120} />
          {visitsChart && visitsChart.labels.length > 0 && (
            <div className="flex justify-between mt-2 text-xs text-gray-400">
              <span>{visitsChart.labels[0]}</span>
              <span>{visitsChart.labels[visitsChart.labels.length - 1]}</span>
            </div>
          )}
        </div>

        <div className="bg-white rounded-xl shadow-sm p-5">
          <h3 className="font-semibold text-gray-800 mb-4">Unique Visitors</h3>
          <SimpleBarChart data={uniqueChart} color="bg-green-500" height={120} />
          {uniqueChart && uniqueChart.labels.length > 0 && (
            <div className="flex justify-between mt-2 text-xs text-gray-400">
              <span>{uniqueChart.labels[0]}</span>
              <span>{uniqueChart.labels[uniqueChart.labels.length - 1]}</span>
            </div>
          )}
        </div>
      </div>

      {/* Breakdowns */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <BreakdownCard
          title="By Device"
          data={overview?.device_breakdown || {}}
          icon="&#128187;"
        />
        <BreakdownCard
          title="By Browser"
          data={overview?.browser_breakdown || {}}
          icon="&#127760;"
        />
        <BreakdownCard
          title="By Country"
          data={overview?.country_breakdown || {}}
          icon="&#127757;"
          nameMap={countryNames}
        />
      </div>

      {/* Tables */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Top Pages */}
        <div className="bg-white rounded-xl shadow-sm p-5">
          <h3 className="font-semibold text-gray-800 mb-4">Top Pages</h3>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="text-left text-xs text-gray-500 uppercase border-b">
                  <th className="pb-2 pr-2">#</th>
                  <th className="pb-2">Page</th>
                  <th className="pb-2 text-right">Views</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {topPages.length === 0 ? (
                  <tr>
                    <td colSpan={3} className="py-4 text-center text-gray-400">
                      No data
                    </td>
                  </tr>
                ) : (
                  topPages.slice(0, 10).map((page, index) => (
                    <tr key={index} className="text-sm hover:bg-gray-50">
                      <td className="py-2 pr-2 text-gray-400">{index + 1}</td>
                      <td className="py-2 text-gray-700 truncate max-w-[250px]" title={page.path}>
                        {page.path}
                      </td>
                      <td className="py-2 text-right text-gray-600 font-medium">{formatNumber(page.views)}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Top Referrers */}
        <div className="bg-white rounded-xl shadow-sm p-5">
          <h3 className="font-semibold text-gray-800 mb-4">Top Referrers</h3>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="text-left text-xs text-gray-500 uppercase border-b">
                  <th className="pb-2 pr-2">#</th>
                  <th className="pb-2">Source</th>
                  <th className="pb-2 text-right">Visits</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {topReferrers.length === 0 ? (
                  <tr>
                    <td colSpan={3} className="py-4 text-center text-gray-400">
                      No referrer data (direct visits)
                    </td>
                  </tr>
                ) : (
                  topReferrers.map((ref, index) => (
                    <tr key={index} className="text-sm hover:bg-gray-50">
                      <td className="py-2 pr-2 text-gray-400">{index + 1}</td>
                      <td className="py-2 text-gray-700">{ref.domain}</td>
                      <td className="py-2 text-right text-gray-600 font-medium">{formatNumber(ref.visits)}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
