"use client";

import { useState, useEffect } from "react";
import {
  Search,
  Filter,
  Download,
  ChevronLeft,
  ChevronRight,
  CheckCircle,
  XCircle,
  RefreshCw,
  Globe,
  MapPin,
} from "lucide-react";

interface LoginEntry {
  id: string;
  userId: string;
  ipAddress: string;
  userAgent: string | null;
  country: string | null;
  countryCode: string | null;
  city: string | null;
  region: string | null;
  latitude: number | null;
  longitude: number | null;
  timezone: string | null;
  provider: string;
  success: boolean;
  failReason: string | null;
  createdAt: string;
  user: {
    id: string;
    email: string;
    name: string | null;
  };
}

interface CountryData {
  country: string;
  countryCode: string;
  count: number;
  successCount: number;
  failCount: number;
}

interface Filters {
  success: string;
  country: string;
  ip: string;
  startDate: string;
  endDate: string;
}

export default function LoginActivityTable() {
  const [entries, setEntries] = useState<LoginEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);
  const [countries, setCountries] = useState<string[]>([]);
  const [countryData, setCountryData] = useState<CountryData[]>([]);
  const [showFilters, setShowFilters] = useState(false);
  const [viewMode, setViewMode] = useState<"table" | "map">("table");
  const [filters, setFilters] = useState<Filters>({
    success: "",
    country: "",
    ip: "",
    startDate: "",
    endDate: "",
  });

  useEffect(() => {
    fetchCountries();
    fetchCountryData();
  }, []);

  useEffect(() => {
    fetchEntries();
  }, [page, filters]);

  const fetchCountries = async () => {
    try {
      const response = await fetch(
        "/api/staff/dashboard/security/login-history?action=countries",
      );
      if (response.ok) {
        const data = await response.json();
        setCountries(data.countries);
      }
    } catch (error) {
      console.error("Failed to fetch countries:", error);
    }
  };

  const fetchCountryData = async () => {
    try {
      const response = await fetch(
        "/api/staff/dashboard/security/login-history?action=by-country&days=30",
      );
      if (response.ok) {
        const data = await response.json();
        setCountryData(data.data);
      }
    } catch (error) {
      console.error("Failed to fetch country data:", error);
    }
  };

  const fetchEntries = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: "25",
      });

      if (filters.success) params.append("success", filters.success);
      if (filters.country) params.append("country", filters.country);
      if (filters.ip) params.append("ip", filters.ip);
      if (filters.startDate) params.append("startDate", filters.startDate);
      if (filters.endDate) params.append("endDate", filters.endDate);

      const response = await fetch(
        `/api/staff/dashboard/security/login-history?${params}`,
      );
      if (response.ok) {
        const data = await response.json();
        setEntries(data.history);
        setTotalPages(data.totalPages);
        setTotal(data.total);
      }
    } catch (error) {
      console.error("Failed to fetch login history:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleExport = async () => {
    const params = new URLSearchParams({ action: "export" });

    if (filters.success) params.append("success", filters.success);
    if (filters.country) params.append("country", filters.country);
    if (filters.ip) params.append("ip", filters.ip);
    if (filters.startDate) params.append("startDate", filters.startDate);
    if (filters.endDate) params.append("endDate", filters.endDate);

    window.location.href = `/api/staff/dashboard/security/login-history?${params}`;
  };

  const clearFilters = () => {
    setFilters({
      success: "",
      country: "",
      ip: "",
      startDate: "",
      endDate: "",
    });
    setPage(1);
  };

  const hasActiveFilters = Object.values(filters).some((v) => v !== "");

  return (
    <div className="space-y-4">
      {/* Toolbar */}
      <div className="flex flex-wrap items-center gap-3">
        {/* View Mode Toggle */}
        <div className="flex bg-gray-100 rounded-lg p-1">
          <button
            onClick={() => setViewMode("table")}
            className={`px-3 py-1.5 text-sm font-medium rounded-md transition ${
              viewMode === "table"
                ? "bg-white text-brand-ink shadow-sm"
                : "text-gray-600 hover:text-gray-800"
            }`}
          >
            Table
          </button>
          <button
            onClick={() => setViewMode("map")}
            className={`px-3 py-1.5 text-sm font-medium rounded-md transition ${
              viewMode === "map"
                ? "bg-white text-brand-ink shadow-sm"
                : "text-gray-600 hover:text-gray-800"
            }`}
          >
            By Country
          </button>
        </div>

        <div className="flex-1" />

        {/* Filter toggle */}
        <button
          onClick={() => setShowFilters(!showFilters)}
          className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition ${
            showFilters || hasActiveFilters
              ? "bg-brand-green text-white"
              : "bg-gray-100 text-gray-700 hover:bg-gray-200"
          }`}
        >
          <Filter className="w-4 h-4" />
          Filters
          {hasActiveFilters && (
            <span className="bg-white/20 text-white text-xs px-1.5 py-0.5 rounded">
              {Object.values(filters).filter((v) => v !== "").length}
            </span>
          )}
        </button>

        {/* Refresh */}
        <button
          onClick={fetchEntries}
          disabled={loading}
          className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition"
          title="Refresh"
        >
          <RefreshCw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} />
        </button>

        {/* Export */}
        <button
          onClick={handleExport}
          className="flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200 transition"
        >
          <Download className="w-4 h-4" />
          Export CSV
        </button>
      </div>

      {/* Filters Panel */}
      {showFilters && (
        <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                Status
              </label>
              <select
                value={filters.success}
                onChange={(e) => {
                  setFilters({ ...filters, success: e.target.value });
                  setPage(1);
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
              >
                <option value="">All</option>
                <option value="true">Successful</option>
                <option value="false">Failed</option>
              </select>
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                Country
              </label>
              <select
                value={filters.country}
                onChange={(e) => {
                  setFilters({ ...filters, country: e.target.value });
                  setPage(1);
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
              >
                <option value="">All Countries</option>
                {countries.map((country) => (
                  <option key={country} value={country}>
                    {country}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                IP Address
              </label>
              <input
                type="text"
                placeholder="Filter by IP"
                value={filters.ip}
                onChange={(e) => {
                  setFilters({ ...filters, ip: e.target.value });
                  setPage(1);
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                Date Range
              </label>
              <div className="flex gap-2">
                <input
                  type="date"
                  value={filters.startDate}
                  onChange={(e) => {
                    setFilters({ ...filters, startDate: e.target.value });
                    setPage(1);
                  }}
                  className="w-full px-2 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
                />
                <input
                  type="date"
                  value={filters.endDate}
                  onChange={(e) => {
                    setFilters({ ...filters, endDate: e.target.value });
                    setPage(1);
                  }}
                  className="w-full px-2 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
                />
              </div>
            </div>

            <div className="flex items-end">
              <button
                onClick={clearFilters}
                className="w-full px-3 py-2 text-sm text-gray-600 hover:text-gray-800 border border-gray-300 rounded-lg hover:bg-gray-100 transition"
              >
                Clear All
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Results count */}
      <div className="text-sm text-gray-500">
        {total.toLocaleString()} login entries
      </div>

      {viewMode === "table" ? (
        <>
          {/* Table */}
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
                  <th className="pb-3 pr-4">Timestamp</th>
                  <th className="pb-3 pr-4">User</th>
                  <th className="pb-3 pr-4">Status</th>
                  <th className="pb-3 pr-4">Location</th>
                  <th className="pb-3 pr-4">IP Address</th>
                  <th className="pb-3 pr-4">Provider</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {loading ? (
                  <tr>
                    <td colSpan={6} className="py-12 text-center text-gray-500">
                      <RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2" />
                      Loading login history...
                    </td>
                  </tr>
                ) : entries.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="py-12 text-center text-gray-500">
                      No login history found
                    </td>
                  </tr>
                ) : (
                  entries.map((entry) => (
                    <tr key={entry.id} className="hover:bg-gray-50">
                      <td className="py-3 pr-4">
                        <div className="text-sm text-brand-ink">
                          {new Date(entry.createdAt).toLocaleDateString()}
                        </div>
                        <div className="text-xs text-gray-500">
                          {new Date(entry.createdAt).toLocaleTimeString()}
                        </div>
                      </td>
                      <td className="py-3 pr-4">
                        <div className="text-sm font-medium text-brand-ink">
                          {entry.user.name || "Unknown"}
                        </div>
                        <div className="text-xs text-gray-500">
                          {entry.user.email}
                        </div>
                      </td>
                      <td className="py-3 pr-4">
                        {entry.success ? (
                          <span className="inline-flex items-center gap-1 text-xs font-medium text-green-700">
                            <CheckCircle className="w-3.5 h-3.5" />
                            Success
                          </span>
                        ) : (
                          <div>
                            <span className="inline-flex items-center gap-1 text-xs font-medium text-red-700">
                              <XCircle className="w-3.5 h-3.5" />
                              Failed
                            </span>
                            {entry.failReason && (
                              <div className="text-xs text-red-500 mt-0.5">
                                {entry.failReason}
                              </div>
                            )}
                          </div>
                        )}
                      </td>
                      <td className="py-3 pr-4">
                        {entry.country ? (
                          <div className="flex items-center gap-1.5">
                            <MapPin className="w-3.5 h-3.5 text-gray-400" />
                            <div>
                              <div className="text-sm text-brand-ink">
                                {entry.city ? `${entry.city}, ` : ""}
                                {entry.country}
                              </div>
                              {entry.region && (
                                <div className="text-xs text-gray-500">
                                  {entry.region}
                                </div>
                              )}
                            </div>
                          </div>
                        ) : (
                          <span className="text-sm text-gray-400">Unknown</span>
                        )}
                      </td>
                      <td className="py-3 pr-4">
                        <span className="text-sm text-gray-600 font-mono">
                          {entry.ipAddress}
                        </span>
                      </td>
                      <td className="py-3 pr-4">
                        <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-700 capitalize">
                          {entry.provider}
                        </span>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between pt-4 border-t border-gray-200">
              <p className="text-sm text-gray-500">
                Page {page} of {totalPages}
              </p>
              <div className="flex gap-2">
                <button
                  onClick={() => setPage(page - 1)}
                  disabled={page === 1}
                  className="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <ChevronLeft className="w-4 h-4" />
                  Previous
                </button>
                <button
                  onClick={() => setPage(page + 1)}
                  disabled={page === totalPages}
                  className="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Next
                  <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            </div>
          )}
        </>
      ) : (
        /* Country View */
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {countryData.map((data) => (
              <div
                key={data.countryCode}
                className="bg-white border border-gray-200 rounded-xl p-4 hover:shadow-md transition"
              >
                <div className="flex items-center gap-3 mb-3">
                  <div className="w-10 h-10 bg-gray-100 rounded-lg flex items-center justify-center">
                    <Globe className="w-5 h-5 text-gray-600" />
                  </div>
                  <div>
                    <h4 className="font-semibold text-brand-ink">
                      {data.country}
                    </h4>
                    <p className="text-xs text-gray-500">{data.countryCode}</p>
                  </div>
                  <div className="ml-auto text-right">
                    <p className="text-2xl font-bold text-brand-ink">
                      {data.count}
                    </p>
                    <p className="text-xs text-gray-500">logins</p>
                  </div>
                </div>
                <div className="flex gap-4 text-sm">
                  <div className="flex items-center gap-1.5">
                    <CheckCircle className="w-4 h-4 text-green-500" />
                    <span className="text-green-700">
                      {data.successCount} success
                    </span>
                  </div>
                  <div className="flex items-center gap-1.5">
                    <XCircle className="w-4 h-4 text-red-500" />
                    <span className="text-red-700">
                      {data.failCount} failed
                    </span>
                  </div>
                </div>
                <div className="mt-3">
                  <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-green-500"
                      style={{
                        width: `${(data.successCount / data.count) * 100}%`,
                      }}
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
          {countryData.length === 0 && (
            <div className="text-center py-12 text-gray-500">
              No login data by country available
            </div>
          )}
        </div>
      )}
    </div>
  );
}
