"use client";

import { useState, useEffect } from "react";

type VisitorEntry = {
  url: string;
  timestamp: number;
  userAgent?: string;
  referer?: string;
};

type VisitorsData = {
  entries: VisitorEntry[];
  totalVisitors?: number;
};

export function VisitorsTab() {
  const [visitors, setVisitors] = useState<VisitorsData>({ entries: [] });
  const [loading, setLoading] = useState(true);

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

  const loadVisitors = async () => {
    try {
      const res = await fetch("/api/admin/visitors");
      if (res.ok) {
        const data = await res.json();
        setVisitors(data);
      }
    } catch (error) {
      console.error("Failed to load visitors:", error);
    } finally {
      setLoading(false);
    }
  };

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

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

      if (res.ok) {
        setVisitors({ entries: [], totalVisitors: 0 });
        alert("Visitor data reset successfully!");
      } else {
        alert("Failed to reset visitor data");
      }
    } catch (error) {
      alert("Failed to reset visitor data");
    }
  };

  const formatTimestamp = (timestamp: number) => {
    const date = new Date(timestamp);
    return date.toLocaleString();
  };

  const truncateUrl = (url: string, maxLength: number = 80) => {
    if (url.length <= maxLength) return url;
    return url.substring(0, maxLength) + "...";
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-lg text-slate-600">Loading visitor 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">Visitors</h2>
          <p className="mt-1 text-sm text-slate-600">
            Track entry URLs of visitors. 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 items-center justify-between">
            <h3 className="text-lg font-semibold text-slate-900">
              Total Visitors: <span className="text-blue-600">{(visitors.totalVisitors ?? visitors.entries.length).toLocaleString()}</span>
            </h3>
            <span className="text-sm text-slate-500">
              Showing last 100 entries
            </span>
          </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">
                  #
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-700">
                  Entry URL
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-700">
                  Referer
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-700">
                  User Agent
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-700">
                  Timestamp
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200 bg-white">
              {visitors.entries.length === 0 ? (
                <tr>
                  <td colSpan={5} className="px-6 py-12 text-center text-sm text-slate-500">
                    No visitors tracked yet.
                  </td>
                </tr>
              ) : (
                visitors.entries.slice(0, 100).map((entry, index) => (
                  <tr
                    key={`${entry.timestamp}-${index}`}
                    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="px-6 py-4 text-sm text-slate-900">
                      <a
                        href={entry.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-blue-600 hover:text-blue-800 hover:underline break-all"
                        title={entry.url}
                      >
                        {truncateUrl(entry.url)}
                      </a>
                    </td>
                    <td className="px-6 py-4 text-sm text-slate-600">
                      {entry.referer ? (
                        <a
                          href={entry.referer}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-blue-600 hover:text-blue-800 hover:underline break-all"
                          title={entry.referer}
                        >
                          {truncateUrl(entry.referer, 60)}
                        </a>
                      ) : (
                        <span className="text-slate-400 italic">No referer</span>
                      )}
                    </td>
                    <td className="px-6 py-4 text-sm text-slate-600">
                      <span className="break-all" title={entry.userAgent || "Unknown"}>
                        {entry.userAgent ? truncateUrl(entry.userAgent, 50) : "Unknown"}
                      </span>
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-sm text-slate-600">
                      {formatTimestamp(entry.timestamp)}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

