"use client";

import { Users, Copy, Check, MapPin, Briefcase } from "lucide-react";
import { useState } from "react";

export interface UserData {
  id: string;
  name: string;
  email: string;
  role: string;
  country: string | null;
  city: string | null;
  ipAddress: string | null;
  companyName: string | null;
  industry: string | null;
  status: "active" | "suspended" | "locked";
  loginCount: number;
  lastLoginAt: string | null;
  createdAt: string;
  organizationName?: string | null;
  organizationRole?: string | null;
}

interface UserTableProps {
  users: UserData[];
  onUserClick: (user: UserData) => void;
  onQuickAction?: (userId: string, action: "suspend" | "activate") => void;
  canPerformActions: boolean;
}

export default function UserTable({
  users,
  onUserClick,
  onQuickAction,
  canPerformActions,
}: UserTableProps) {
  const [copiedEmail, setCopiedEmail] = useState<string | null>(null);
  const [copiedIp, setCopiedIp] = useState<string | null>(null);

  const copyToClipboard = async (text: string, type: "email" | "ip") => {
    try {
      await navigator.clipboard.writeText(text);
      if (type === "email") {
        setCopiedEmail(text);
        setTimeout(() => setCopiedEmail(null), 2000);
      } else {
        setCopiedIp(text);
        setTimeout(() => setCopiedIp(null), 2000);
      }
    } catch (err) {
      console.error("Failed to copy:", err);
    }
  };

  const getStatusBadge = (status: string) => {
    const badges = {
      active: "bg-green-100 text-green-800 border-green-200",
      suspended: "bg-orange-100 text-orange-800 border-orange-200",
      locked: "bg-red-100 text-red-800 border-red-200",
    };
    return badges[status as keyof typeof badges] || badges.active;
  };

  const getRoleBadge = (role: string) => {
    const badges: Record<string, { bg: string; text: string; label: string }> =
      {
        CUSTOMER: {
          bg: "bg-gray-100",
          text: "text-gray-700",
          label: "Customer",
        },
        STAFF: { bg: "bg-blue-100", text: "text-blue-700", label: "Staff" },
        ADMIN: { bg: "bg-purple-100", text: "text-purple-700", label: "Admin" },
        SUPER_ADMIN: {
          bg: "bg-red-100",
          text: "text-red-700",
          label: "Super Admin",
        },
      };
    return badges[role] || badges.CUSTOMER;
  };

  const formatDate = (dateString: string | null) => {
    if (!dateString) return "Never";
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  if (users.length === 0) {
    return (
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12">
        <div className="text-center">
          <Users className="w-16 h-16 text-gray-300 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            No users found
          </h3>
          <p className="text-gray-600">
            Try adjusting your filters or search criteria
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead className="bg-gray-50 border-b border-gray-200">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                User
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Role / Status
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Company / Industry
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Location / IP
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Activity
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Last Login
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {users.map((user) => (
              <tr
                key={user.id}
                onClick={() => onUserClick(user)}
                className="hover:bg-gray-50 transition cursor-pointer"
              >
                {/* User */}
                <td className="px-6 py-4">
                  <div>
                    <p className="text-sm font-medium text-brand-ink">
                      {user.name}
                    </p>
                    <div className="flex items-center gap-1 group">
                      <p className="text-xs text-gray-500">{user.email}</p>
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          copyToClipboard(user.email, "email");
                        }}
                        className="opacity-0 group-hover:opacity-100 transition"
                        title="Copy email"
                      >
                        {copiedEmail === user.email ? (
                          <Check className="w-3 h-3 text-green-600" />
                        ) : (
                          <Copy className="w-3 h-3 text-gray-400 hover:text-gray-600" />
                        )}
                      </button>
                    </div>
                  </div>
                </td>

                {/* Role / Status */}
                <td className="px-6 py-4">
                  <div className="flex flex-col gap-1">
                    <span
                      className={`inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-md ${getRoleBadge(user.role).bg} ${getRoleBadge(user.role).text}`}
                    >
                      {getRoleBadge(user.role).label}
                    </span>
                    <span
                      className={`inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-md border ${getStatusBadge(user.status)}`}
                    >
                      {user.status}
                    </span>
                    {user.organizationName && (
                      <span className="text-xs text-gray-500 mt-0.5">
                        {user.organizationName}
                        {user.organizationRole &&
                          user.organizationRole !== "OWNER" && (
                            <span className="text-gray-400">
                              {" "}
                              ({user.organizationRole})
                            </span>
                          )}
                      </span>
                    )}
                  </div>
                </td>

                {/* Company / Industry */}
                <td className="px-6 py-4">
                  <div>
                    <p className="text-sm text-gray-900 flex items-center gap-1">
                      <Briefcase className="w-3 h-3 text-gray-400" />
                      {user.companyName || "-"}
                    </p>
                    {user.industry && (
                      <p className="text-xs text-gray-500 mt-1">
                        {user.industry}
                      </p>
                    )}
                  </div>
                </td>

                {/* Location / IP */}
                <td className="px-6 py-4">
                  <div>
                    {user.country && (
                      <p className="text-sm text-gray-900 flex items-center gap-1">
                        <MapPin className="w-3 h-3 text-gray-400" />
                        {user.city
                          ? `${user.city}, ${user.country}`
                          : user.country}
                      </p>
                    )}
                    {user.ipAddress && (
                      <div className="flex items-center gap-1 group mt-1">
                        <p className="text-xs text-gray-500 font-mono">
                          {user.ipAddress}
                        </p>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            copyToClipboard(user.ipAddress!, "ip");
                          }}
                          className="opacity-0 group-hover:opacity-100 transition"
                          title="Copy IP"
                        >
                          {copiedIp === user.ipAddress ? (
                            <Check className="w-3 h-3 text-green-600" />
                          ) : (
                            <Copy className="w-3 h-3 text-gray-400 hover:text-gray-600" />
                          )}
                        </button>
                      </div>
                    )}
                  </div>
                </td>

                {/* Activity */}
                <td className="px-6 py-4">
                  <div className="text-sm text-gray-900">
                    <p className="font-medium">{user.loginCount} logins</p>
                    <p className="text-xs text-gray-500">
                      Since {new Date(user.createdAt).toLocaleDateString()}
                    </p>
                  </div>
                </td>

                {/* Last Login */}
                <td className="px-6 py-4">
                  <p className="text-sm text-gray-900">
                    {formatDate(user.lastLoginAt)}
                  </p>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
