"use client";

import { useEffect, useState, useCallback } from "react";
import { Download, RefreshCw, List, Map as MapIcon } from "lucide-react";
import UserStatsComponent from "./users/UserStats";
import UserFilters, { UserStatus, UserRole } from "./users/UserFilters";
import UserTable, { UserData } from "./users/UserTable";
import UserModal from "./users/UserModal";
import GeographyMap from "./users/GeographyMap";

interface User {
  id: string;
  role: string;
}

interface UserStats {
  total: number;
  active: number;
  suspended: number;
  locked: number;
  topCountry: { name: string; count: number } | null;
  topIndustry: { name: string; count: number } | null;
}

interface CountryData {
  name: string;
  count: number;
  percentage: number;
}

export default function UsersList({ user }: { user: User }) {
  const [users, setUsers] = useState<UserData[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<UserData[]>([]);
  const [stats, setStats] = useState<UserStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [autoRefresh, setAutoRefresh] = useState(false);

  // Filters
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState<UserStatus>("all");
  const [roleFilter, setRoleFilter] = useState<UserRole>("all");
  const [countryFilter, setCountryFilter] = useState("all");

  // View mode
  const [viewMode, setViewMode] = useState<"list" | "map">("list");

  // Modal
  const [selectedUser, setSelectedUser] = useState<UserData | null>(null);

  // Countries for filter
  const [countries, setCountries] = useState<string[]>([]);
  const [geographyData, setGeographyData] = useState<CountryData[]>([]);

  const fetchUsers = useCallback(async (showRefreshIndicator = false) => {
    if (showRefreshIndicator) {
      setRefreshing(true);
    } else {
      setLoading(true);
    }

    try {
      const response = await fetch("/api/staff/dashboard/users");
      if (response.ok) {
        const data = await response.json();

        // Transform API data to match our enhanced structure
        const enhancedUsers: UserData[] = data.users.map((u: any) => ({
          id: u.id,
          name: u.name,
          email: u.email,
          role: u.role || "CUSTOMER",
          country: u.lastLoginCountry || u.country,
          city: u.lastLoginCity || u.city,
          ipAddress: u.lastLoginIp,
          companyName: u.companyName,
          industry: u.industry,
          status: u.accountStatus || "active",
          loginCount: u.loginCount || 0,
          lastLoginAt: u.lastLoginAt,
          createdAt: u.createdAt,
          organizationName: u.organizationName,
          organizationRole: u.organizationRole,
        }));

        setUsers(enhancedUsers);

        // Use analytics data from API
        const enhancedStats: UserStats = {
          total: data.analytics.total || data.stats?.total || 0,
          active: data.analytics.active || 0,
          suspended: data.analytics.suspended || 0,
          locked: data.analytics.locked || 0,
          topCountry:
            Object.entries(
              data.analytics?.byCountry || data.stats?.byCountry || {},
            ).length > 0
              ? {
                  name: Object.entries(
                    data.analytics?.byCountry || data.stats?.byCountry || {},
                  ).sort((a: any, b: any) => b[1] - a[1])[0][0],
                  count: Object.entries(
                    data.analytics?.byCountry || data.stats?.byCountry || {},
                  ).sort((a: any, b: any) => b[1] - a[1])[0][1] as number,
                }
              : null,
          topIndustry:
            Object.entries(
              data.analytics?.byIndustry || data.stats?.byPackage || {},
            ).length > 0
              ? {
                  name: Object.entries(
                    data.analytics?.byIndustry || data.stats?.byPackage || {},
                  ).sort((a: any, b: any) => b[1] - a[1])[0][0],
                  count: Object.entries(
                    data.analytics?.byIndustry || data.stats?.byPackage || {},
                  ).sort((a: any, b: any) => b[1] - a[1])[0][1] as number,
                }
              : null,
        };

        setStats(enhancedStats);

        // Extract countries for filter
        const uniqueCountries = Array.from(
          new Set(
            enhancedUsers.map((u: UserData) => u.country).filter(Boolean),
          ),
        ) as string[];
        setCountries(uniqueCountries.sort());

        // Prepare geography data
        const countryCount = enhancedUsers.reduce((acc: any, u: UserData) => {
          const country = u.country || "Unknown";
          acc[country] = (acc[country] || 0) + 1;
          return acc;
        }, {});

        const geoData: CountryData[] = Object.entries(countryCount).map(
          ([name, count]) => ({
            name,
            count: count as number,
            percentage: ((count as number) / enhancedUsers.length) * 100,
          }),
        );

        setGeographyData(geoData);
      }
    } catch (error) {
      console.error("Failed to fetch users:", error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

  // Apply filters
  useEffect(() => {
    let filtered = [...users];

    // Search filter
    if (search) {
      const searchLower = search.toLowerCase();
      filtered = filtered.filter(
        (u) =>
          u.name.toLowerCase().includes(searchLower) ||
          u.email.toLowerCase().includes(searchLower) ||
          u.companyName?.toLowerCase().includes(searchLower),
      );
    }

    // Status filter
    if (statusFilter !== "all") {
      filtered = filtered.filter((u) => u.status === statusFilter);
    }

    // Role filter
    if (roleFilter !== "all") {
      filtered = filtered.filter((u) => u.role === roleFilter);
    }

    // Country filter
    if (countryFilter !== "all") {
      filtered = filtered.filter((u) => u.country === countryFilter);
    }

    setFilteredUsers(filtered);
  }, [users, search, statusFilter, roleFilter, countryFilter]);

  // Initial fetch
  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);

  // Auto-refresh every 30 seconds
  useEffect(() => {
    if (!autoRefresh) return;

    const interval = setInterval(() => {
      fetchUsers(true);
    }, 30000);

    return () => clearInterval(interval);
  }, [autoRefresh, fetchUsers]);

  const handleClearFilters = () => {
    setSearch("");
    setStatusFilter("all");
    setRoleFilter("all");
    setCountryFilter("all");
  };

  const filterCount = [
    search !== "",
    statusFilter !== "all",
    roleFilter !== "all",
    countryFilter !== "all",
  ].filter(Boolean).length;

  const handleExportCSV = () => {
    const csvData = filteredUsers.map((u) => ({
      Name: u.name,
      Email: u.email,
      Role: u.role,
      Status: u.status,
      Company: u.companyName || "",
      Industry: u.industry || "",
      Country: u.country || "",
      "Login Count": u.loginCount,
      "Last Login": u.lastLoginAt ? new Date(u.lastLoginAt).toISOString() : "",
      Registered: new Date(u.createdAt).toISOString(),
    }));

    const headers = Object.keys(csvData[0] || {});
    const csvRows = [
      headers.join(","),
      ...csvData.map((row) =>
        headers
          .map((header) => `"${row[header as keyof typeof row]}"`)
          .join(","),
      ),
    ];

    const csvString = csvRows.join("\n");
    const blob = new Blob([csvString], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `users-export-${new Date().toISOString().split("T")[0]}.csv`;
    link.click();
    URL.revokeObjectURL(url);
  };

  const handleCountryClick = (country: string) => {
    setCountryFilter(country);
    setViewMode("list");
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <div className="w-12 h-12 border-4 border-brand-green border-t-transparent rounded-full animate-spin mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading users...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Stats Cards */}
      {stats && <UserStatsComponent stats={stats} />}

      {/* Filters */}
      <UserFilters
        search={search}
        onSearchChange={setSearch}
        status={statusFilter}
        onStatusChange={setStatusFilter}
        role={roleFilter}
        onRoleChange={setRoleFilter}
        country={countryFilter}
        onCountryChange={setCountryFilter}
        countries={countries}
        onClearFilters={handleClearFilters}
        filterCount={filterCount}
      />

      {/* View Controls */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <button
              onClick={() => setViewMode("list")}
              className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition ${
                viewMode === "list"
                  ? "bg-brand-green text-white"
                  : "text-gray-700 bg-gray-100 hover:bg-gray-200"
              }`}
            >
              <List className="w-4 h-4" />
              List View
            </button>
            <button
              onClick={() => setViewMode("map")}
              className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition ${
                viewMode === "map"
                  ? "bg-brand-green text-white"
                  : "text-gray-700 bg-gray-100 hover:bg-gray-200"
              }`}
            >
              <MapIcon className="w-4 h-4" />
              Map View
            </button>
          </div>

          <div className="flex items-center gap-2">
            <label className="flex items-center gap-2 text-sm text-gray-700">
              <input
                type="checkbox"
                checked={autoRefresh}
                onChange={(e) => setAutoRefresh(e.target.checked)}
                className="rounded border-gray-300 text-brand-green focus:ring-brand-green"
              />
              Auto-refresh
            </label>

            <button
              onClick={() => fetchUsers(true)}
              disabled={refreshing}
              className="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 disabled:opacity-50"
            >
              <RefreshCw
                className={`w-4 h-4 ${refreshing ? "animate-spin" : ""}`}
              />
              Refresh
            </button>

            {user.role !== "STAFF" && (
              <button
                onClick={handleExportCSV}
                className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-green-700"
              >
                <Download className="w-4 h-4" />
                Export CSV
              </button>
            )}
          </div>
        </div>

        {/* Results count */}
        <div className="mt-3 pt-3 border-t border-gray-200">
          <p className="text-sm text-gray-600">
            Showing{" "}
            <span className="font-semibold text-brand-ink">
              {filteredUsers.length}
            </span>{" "}
            of{" "}
            <span className="font-semibold text-brand-ink">{users.length}</span>{" "}
            users
          </p>
        </div>
      </div>

      {/* Content */}
      {viewMode === "list" ? (
        <UserTable
          users={filteredUsers}
          onUserClick={setSelectedUser}
          canPerformActions={
            user.role === "ADMIN" || user.role === "SUPER_ADMIN"
          }
        />
      ) : (
        <GeographyMap
          data={geographyData}
          onCountryClick={handleCountryClick}
        />
      )}

      {/* User Modal */}
      {selectedUser && (
        <UserModal
          user={selectedUser}
          onClose={() => setSelectedUser(null)}
          onSuspend={(userId, reason) => {
            console.log("Suspend user:", userId, reason);
            setSelectedUser(null);
            fetchUsers(true);
          }}
          onActivate={(userId) => {
            console.log("Activate user:", userId);
            setSelectedUser(null);
            fetchUsers(true);
          }}
          isAdmin={user.role === "ADMIN" || user.role === "SUPER_ADMIN"}
        />
      )}
    </div>
  );
}
