"use client";

import React, { useEffect, useState, useCallback } from "react";
import toast from "react-hot-toast";
import {
  FiShield,
  FiUserPlus,
  FiLock,
  FiUnlock,
  FiAlertTriangle,
  FiRefreshCw,
  FiMail,
  FiClock,
} from "react-icons/fi";
import {
  getPortalUsers,
  disablePortalAccess,
  enablePortalAccess,
  disableAllPortalAccess,
} from "@/lib/api/company.api";
import type { PortalUser, PortalUserStatus } from "@/lib/api/types/company.types";

interface Props {
  companyId: number;
  companyName: string;
  onInviteClick: () => void;
}

const STATUS_CONFIG: Record<
  PortalUserStatus,
  { label: string; bg: string; color: string; dot: string }
> = {
  ACTIVE: { label: "Active", bg: "#f0fdf4", color: "#15803d", dot: "#22c55e" },
  INVITED: { label: "Invited", bg: "#fffbeb", color: "#b45309", dot: "#f59e0b" },
  DISABLED: { label: "Disabled", bg: "#fef2f2", color: "#b91c1c", dot: "#ef4444" },
};

function formatDate(d: string | null | undefined): string {
  if (!d) return "—";
  return new Date(d).toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function getUserName(user: any): string {
  if (!user) return "—";
  const first = user.firstName || user.first_name || "";
  const last = user.lastName || user.last_name || "";
  const full = `${first} ${last}`.trim();
  return full || user.email || `User #${user.id}`;
}

export default function PortalAccessPanel({
  companyId,
  companyName,
  onInviteClick,
}: Props) {
  const [users, setUsers] = useState<PortalUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState<string | null>(null);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    try {
      const data = await getPortalUsers(companyId);
      setUsers(Array.isArray(data) ? data : []);
    } catch {
      setUsers([]);
    } finally {
      setLoading(false);
    }
  }, [companyId]);

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

  const handleDisable = async (userId: number) => {
    setActionLoading(`disable-${userId}`);
    try {
      await disablePortalAccess(companyId, userId);
      toast.success("Portal access disabled");
      fetchUsers();
    } catch (err: any) {
      toast.error(err?.message || "Failed to disable");
    } finally {
      setActionLoading(null);
    }
  };

  const handleEnable = async (userId: number) => {
    setActionLoading(`enable-${userId}`);
    try {
      await enablePortalAccess(companyId, userId);
      toast.success("Portal access re-enabled");
      fetchUsers();
    } catch (err: any) {
      toast.error(err?.message || "Failed to enable");
    } finally {
      setActionLoading(null);
    }
  };

  const handleDisableAll = async () => {
    if (!confirm(`Disable ALL portal access for ${companyName}? This is instant.`)) return;
    setActionLoading("disable-all");
    try {
      const res = await disableAllPortalAccess(companyId);
      toast.success(`${res.disabled} user(s) disabled`);
      fetchUsers();
    } catch (err: any) {
      toast.error(err?.message || "Failed");
    } finally {
      setActionLoading(null);
    }
  };

  const activeCount = users.filter((u) => u.status === "ACTIVE").length;
  const totalCount = users.length;

  return (
    <div>
      {/* Header */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          marginBottom: 12,
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <FiShield size={16} color="#0f766e" />
          <span style={{ fontSize: 14, fontWeight: 600, color: "#111827" }}>
            Client portal access
          </span>
          {!loading && (
            <span
              style={{
                fontSize: 11,
                padding: "2px 8px",
                borderRadius: 10,
                background: activeCount > 0 ? "#f0fdf4" : "#f3f4f6",
                color: activeCount > 0 ? "#15803d" : "#6b7280",
                fontWeight: 600,
              }}
            >
              {activeCount} active / {totalCount} total
            </span>
          )}
        </div>

        <div style={{ display: "flex", gap: 6 }}>
          <button
            onClick={fetchUsers}
            disabled={loading}
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 4,
              padding: "5px 10px",
              border: "1px solid #e5e7eb",
              borderRadius: 6,
              background: "#fff",
              fontSize: 12,
              cursor: "pointer",
              color: "#6b7280",
            }}
          >
            <FiRefreshCw size={12} />
          </button>
          <button
            onClick={onInviteClick}
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 4,
              padding: "5px 12px",
              border: "1px solid #bbf7d0",
              borderRadius: 6,
              background: "#f0fdf4",
              fontSize: 12,
              fontWeight: 600,
              cursor: "pointer",
              color: "#15803d",
            }}
          >
            <FiUserPlus size={12} /> Invite
          </button>
          {activeCount > 0 && (
            <button
              onClick={handleDisableAll}
              disabled={actionLoading === "disable-all"}
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 4,
                padding: "5px 12px",
                border: "1px solid #fecaca",
                borderRadius: 6,
                background: "#fef2f2",
                fontSize: 12,
                fontWeight: 600,
                cursor: "pointer",
                color: "#b91c1c",
              }}
            >
              <FiLock size={12} /> Disable all
            </button>
          )}
        </div>
      </div>

      {/* User list */}
      {loading ? (
        <div
          style={{
            padding: 20,
            textAlign: "center",
            color: "#9ca3af",
            fontSize: 13,
          }}
        >
          Loading portal users...
        </div>
      ) : users.length === 0 ? (
        <div
          style={{
            padding: "16px",
            textAlign: "center",
            color: "#9ca3af",
            fontSize: 13,
            border: "1px dashed #e5e7eb",
            borderRadius: 8,
          }}
        >
          No portal users. Click <strong>Invite</strong> to grant access.
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          {users.map((u) => {
            const cfg = STATUS_CONFIG[u.status] || STATUS_CONFIG.DISABLED;
            const isLoading =
              actionLoading === `disable-${u.user_id}` ||
              actionLoading === `enable-${u.user_id}`;
            return (
              <div
                key={`${u.company_id}-${u.user_id}`}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 10,
                  padding: "10px 12px",
                  border: "1px solid #e5e7eb",
                  borderRadius: 8,
                  background: "#fff",
                }}
              >
                {/* Avatar */}
                <div
                  style={{
                    width: 32,
                    height: 32,
                    borderRadius: "50%",
                    background: cfg.bg,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    fontWeight: 600,
                    fontSize: 12,
                    color: cfg.color,
                    flexShrink: 0,
                  }}
                >
                  {getUserName(u.user)?.[0]?.toUpperCase() || "?"}
                </div>

                {/* Info */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: "#111827" }}>
                    {getUserName(u.user)}
                  </div>
                  <div
                    style={{
                      fontSize: 12,
                      color: "#6b7280",
                      display: "flex",
                      alignItems: "center",
                      gap: 6,
                      flexWrap: "wrap",
                    }}
                  >
                    {u.invite_email && (
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 3 }}>
                        <FiMail size={10} /> {u.invite_email}
                      </span>
                    )}
                    {u.last_login_at && (
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 3 }}>
                        <FiClock size={10} /> Last: {formatDate(u.last_login_at)}
                      </span>
                    )}
                  </div>
                </div>

                {/* Status badge */}
                <span
                  style={{
                    fontSize: 11,
                    padding: "2px 10px",
                    borderRadius: 10,
                    background: cfg.bg,
                    color: cfg.color,
                    fontWeight: 600,
                    flexShrink: 0,
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 4,
                  }}
                >
                  <span
                    style={{
                      width: 6,
                      height: 6,
                      borderRadius: "50%",
                      background: cfg.dot,
                    }}
                  />
                  {cfg.label}
                </span>

                {/* Action button */}
                {u.status === "ACTIVE" || u.status === "INVITED" ? (
                  <button
                    onClick={() => handleDisable(u.user_id)}
                    disabled={isLoading}
                    title="Disable portal access"
                    style={{
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 4,
                      padding: "4px 10px",
                      border: "1px solid #e5e7eb",
                      borderRadius: 6,
                      background: "#fff",
                      fontSize: 11,
                      cursor: isLoading ? "not-allowed" : "pointer",
                      color: "#b91c1c",
                      fontWeight: 500,
                      opacity: isLoading ? 0.5 : 1,
                    }}
                  >
                    <FiLock size={11} /> Disable
                  </button>
                ) : (
                  <button
                    onClick={() => handleEnable(u.user_id)}
                    disabled={isLoading}
                    title="Re-enable portal access"
                    style={{
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 4,
                      padding: "4px 10px",
                      border: "1px solid #bbf7d0",
                      borderRadius: 6,
                      background: "#f0fdf4",
                      fontSize: 11,
                      cursor: isLoading ? "not-allowed" : "pointer",
                      color: "#15803d",
                      fontWeight: 500,
                      opacity: isLoading ? 0.5 : 1,
                    }}
                  >
                    <FiUnlock size={11} /> Enable
                  </button>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* Disabled warning */}
      {users.some((u) => u.status === "DISABLED") && (
        <div
          style={{
            display: "flex",
            gap: 8,
            marginTop: 10,
            padding: "8px 12px",
            background: "#fffbeb",
            border: "1px solid #fde68a",
            borderRadius: 8,
            fontSize: 12,
            color: "#92400e",
          }}
        >
          <FiAlertTriangle size={14} style={{ flexShrink: 0, marginTop: 1 }} />
          <span>
            Disabled users cannot log into the client portal. Click <strong>Enable</strong> to restore access.
          </span>
        </div>
      )}
    </div>
  );
}
