"use client";

import { useState, useEffect } from "react";
import type { Partner } from "@/types/data";

interface ClicksTabProps {
  readonly partners: readonly Partner[];
}

interface VisitorsData {
  entries: Array<{
    url: string;
    timestamp: number;
    userAgent?: string;
    referer?: string;
  }>;
  totalVisitors?: number;
}

export function ClicksTab({ partners }: ClicksTabProps) {
  const [clicks, setClicks] = useState<Record<string, number>>({});
  const [visitors, setVisitors] = useState<VisitorsData>({ entries: [] });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadData();
    // Poll for updates every hour (3600000 milliseconds)
    const interval = setInterval(loadData, 3600000);
    return () => clearInterval(interval);
  }, []);

  const loadData = async () => {
    try {
      const [clicksRes, visitorsRes] = await Promise.all([
        fetch("/api/admin/clicks"),
        fetch("/api/admin/visitors"),
      ]);
      
      if (clicksRes.ok) {
        const clicksData = await clicksRes.json();
        setClicks(clicksData);
      }
      
      if (visitorsRes.ok) {
        const visitorsData = await visitorsRes.json();
        setVisitors(visitorsData);
      }
    } catch (error) {
      console.error("Failed to load data:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleReset = async () => {
    if (!confirm("Are you sure you want to reset all click counts? This action cannot be undone.")) {
      return;
    }

    try {
      const res = await fetch("/api/admin/clicks", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "reset" }),
      });

      if (res.ok) {
        setClicks({});
        alert("Click counts reset successfully!");
      } else {
        alert("Failed to reset click counts");
      }
    } catch (error) {
      alert("Failed to reset click counts");
    }
  };

  // Create a map of all partners (displayed and not displayed) with their click counts
  const partnerClicks = partners.map((partner) => ({
    partner,
    clicks: clicks[partner.name] || 0,
  }));

  // Sort by clicks (descending), then by name
  partnerClicks.sort((a, b) => {
    if (b.clicks !== a.clicks) {
      return b.clicks - a.clicks;
    }
    return a.partner.name.localeCompare(b.partner.name);
  });

  const totalClicks = Object.values(clicks).reduce((sum, count) => sum + count, 0);
  // Use totalVisitors counter if available, otherwise fall back to entries.length (for backward compatibility)
  const totalVisitors = visitors.totalVisitors ?? visitors.entries.length;
  const clickThroughRate = totalVisitors > 0 ? ((totalClicks / totalVisitors) * 100).toFixed(1) : "0.0";

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-lg text-slate-600">Loading click data...</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">Click Tracking</h2>
          <p className="mt-1 text-sm text-slate-600">
            Track partner click counts. Data updates automatically every hour.
          </p>
        </div>
        <button
          onClick={handleReset}
          className="rounded-lg bg-red-600 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-red-700"
        >
          Reset All
        </button>
      </div>

      <div className="rounded-lg border border-slate-200 bg-white shadow-sm">
        <div className="border-b border-slate-200 bg-slate-50 px-6 py-4">
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div className="flex flex-wrap items-center gap-6">
              <h3 className="text-lg font-semibold text-slate-900">
                Total Clicks: <span className="text-blue-600">{totalClicks.toLocaleString()}</span>
              </h3>
              <div className="flex flex-wrap items-center gap-4 text-sm">
                <div className="text-slate-700">
                  <span className="font-medium">Total Visitors:</span>{" "}
                  <span className="font-semibold text-slate-900">{totalVisitors.toLocaleString()}</span>
                </div>
                <div className="text-slate-700">
                  <span className="font-medium">Click-Through Rate:</span>{" "}
                  <span className="font-semibold text-slate-900">{clickThroughRate}%</span>
                </div>
              </div>
            </div>
            <span className="text-sm text-slate-500">
              {partnerClicks.filter((pc) => pc.clicks > 0).length} partners with clicks
            </span>
          </div>
          <div className="mt-3 text-xs text-slate-600">
            <p>Shows how many users visited the site and how many users clicked on a link</p>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-700">
                  Rank
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-700">
                  Partner Name
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-700">
                  Status
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium uppercase tracking-wider text-slate-700">
                  Clicks
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium uppercase tracking-wider text-slate-700">
                  Percentage
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200 bg-white">
              {partnerClicks.map(({ partner, clicks: clickCount }, index) => {
                const percentage = totalClicks > 0 ? ((clickCount / totalClicks) * 100).toFixed(1) : "0.0";
                return (
                  <tr
                    key={partner.name}
                    className="transition-colors hover:bg-slate-50"
                  >
                    <td className="whitespace-nowrap px-6 py-4 text-sm font-medium text-slate-900">
                      {index + 1}
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-sm font-semibold text-slate-900">
                      {partner.name}
                    </td>
                    <td className="whitespace-nowrap px-6 py-4">
                      {partner.display !== false ? (
                        <span className="inline-flex rounded-full bg-green-100 px-2 py-1 text-xs font-medium text-green-800">
                          Displayed
                        </span>
                      ) : (
                        <span className="inline-flex rounded-full bg-slate-100 px-2 py-1 text-xs font-medium text-slate-600">
                          Hidden
                        </span>
                      )}
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-right text-sm font-bold text-slate-900">
                      {clickCount.toLocaleString()}
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-right text-sm text-slate-600">
                      {percentage}%
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {partnerClicks.length === 0 && (
          <div className="px-6 py-12 text-center">
            <p className="text-sm text-slate-500">No partners found.</p>
          </div>
        )}
      </div>
    </div>
  );
}

