"use client";

import React from "react";
import styles from "../commonstyle/dattabale.module.css";
import {
  FiEye,
  FiUserCheck,
  FiUserX,
  FiSend,
  FiFileText,
  FiActivity,
} from "react-icons/fi";
import {
  PortalStatusBadge,
  RoleBadge,
  SchemeBadge,
} from "./components/ClientPortalBadges";
import type { PortalClientRow } from "./client-portal.api";

interface Props {
  row: PortalClientRow;
  isSelected: boolean;
  handleRowSelect: (sno: number, checked: boolean) => void;
  onViewLog: (row: PortalClientRow) => void;
  onEnable: (row: PortalClientRow) => void;
  onDisable: (row: PortalClientRow) => void;
  onResendInvite: (row: PortalClientRow) => void;
  onToggleReport: (row: PortalClientRow) => void;
  permittedActions: Set<string>;
  loadingAction: number | null; // user_id currently loading
}

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

function formatDateTime(d: string | null): string {
  if (!d) return "Never";
  try {
    const dt = new Date(d);
    return `${dt.toLocaleDateString("en-GB", {
      day: "2-digit",
      month: "short",
      year: "numeric",
    })} ${dt.toLocaleTimeString("en-GB", {
      hour: "2-digit",
      minute: "2-digit",
    })}`;
  } catch {
    return d;
  }
}

export default function ClientPortalRow({
  row,
  isSelected,
  handleRowSelect,
  onViewLog,
  onEnable,
  onDisable,
  onResendInvite,
  onToggleReport,
  permittedActions,
  loadingAction,
}: Props) {
  const isLoading = loadingAction === row.user_id;

  const showEnable =
    permittedActions.has("enable") && row.status === "DISABLED";
  const showDisable =
    permittedActions.has("disable") && row.status === "ACTIVE";
  const showResend =
    permittedActions.has("resend-invite") &&
    (row.status === "INVITED" || row.status === "DISABLED");
  const showToggleReport =
    permittedActions.has("toggle-report") && row.status === "ACTIVE";
  const showLog =
    permittedActions.has("view-log") || permittedActions.has("view");

  // Status-based row tint
  const cellStyle: React.CSSProperties =
    row.status === "DISABLED" && !isSelected
      ? { background: "#fef2f2" }
      : row.status === "INVITED" && !isSelected
        ? { background: "#fffbeb" }
        : {};

  return (
    <tr
      className={`${styles.tableRow} ${isSelected ? styles.selectedRow : ""}`}
      style={
        row.status === "DISABLED" && !isSelected
          ? { borderLeft: "4px solid #ef4444" }
          : row.status === "INVITED" && !isSelected
            ? { borderLeft: "4px solid #f59e0b" }
            : undefined
      }
    >
      {/* Checkbox */}
      <td
        style={{ textAlign: "center", padding: "10px 8px", ...cellStyle }}
      >
        <input
          type="checkbox"
          className={styles.checkbox}
          checked={isSelected}
          onChange={(e) => handleRowSelect(row.sno, e.target.checked)}
        />
      </td>

      {/* Company */}
      <td className={styles.nameCell} style={cellStyle}>
        <div style={{ fontWeight: 700, fontSize: 13, color: "#0f172a" }}>
          {row.company_name}
        </div>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 4,
            marginTop: 3,
          }}
        >
          <SchemeBadge scheme={row.company?.scheme} />
        </div>
      </td>

      {/* Client Name / Email */}
      <td className={styles.nameCell} style={cellStyle}>
        <div style={{ fontWeight: 600, fontSize: 13, color: "#0f172a" }}>
          👤 {row.client_name}
        </div>
        <div style={{ fontSize: 11, color: "#64748b", marginTop: 2 }}>
          ✉️ {row.client_email}
        </div>
      </td>

      {/* Role */}
      <td className={styles.nameCell} style={cellStyle}>
        <RoleBadge role={row.role} />
      </td>

      {/* Status */}
      <td className={styles.nameCell} style={cellStyle}>
        <PortalStatusBadge status={row.status} />
        {row.status === "INVITED" && (
          <div
            style={{
              marginTop: 4,
              fontSize: 11,
              fontWeight: 700,
              color: "#b45309",
              display: "inline-flex",
              alignItems: "center",
              gap: 4,
            }}
          >
            ⏳ Pending OTP
          </div>
        )}
      </td>

      {/* Granted By */}
      <td className={styles.nameCell} style={cellStyle}>
        <div style={{ fontSize: 12, color: "#374151" }}>
          {row.granted_by_name}
        </div>
        <div style={{ fontSize: 11, color: "#9ca3af", marginTop: 2 }}>
          {formatDate(row.created_at)}
        </div>
      </td>

      {/* Last Login */}
      <td className={styles.nameCell} style={cellStyle}>
        <div
          style={{
            fontSize: 12,
            color: row.last_login_at ? "#0f172a" : "#9ca3af",
            fontStyle: row.last_login_at ? "normal" : "italic",
          }}
        >
          {formatDateTime(row.last_login_at)}
        </div>
      </td>

      {/* Actions */}
      <td className={styles.actionsCell} style={cellStyle}>
        <div className={styles.actionGroup}>
          {/* View Activity Log */}
          {showLog && (
            <button
              className={styles.actionBtnView}
              onClick={() => onViewLog(row)}
              title="View client activity log"
              disabled={isLoading}
            >
              <FiActivity size={14} />
            </button>
          )}

          {/* Enable Access */}
          {showEnable && (
            <button
              className={styles.actionBtnView}
              onClick={() => onEnable(row)}
              title="Re-enable portal access"
              disabled={isLoading}
              style={{
                background: "#dcfce7",
                borderColor: "#86efac",
                color: "#166534",
              }}
            >
              <FiUserCheck size={14} />
            </button>
          )}

          {/* Disable Access */}
          {showDisable && (
            <button
              className={styles.actionBtnView}
              onClick={() => onDisable(row)}
              title="Disable portal access"
              disabled={isLoading}
              style={{
                background: "#fee2e2",
                borderColor: "#fca5a5",
                color: "#991b1b",
              }}
            >
              <FiUserX size={14} />
            </button>
          )}

          {/* Resend Invitation */}
          {showResend && (
            <button
              className={styles.actionBtnView}
              onClick={() => onResendInvite(row)}
              title="Resend invitation email"
              disabled={isLoading}
              style={{
                background: "#fef3c7",
                borderColor: "#fcd34d",
                color: "#92400e",
              }}
            >
              <FiSend size={14} />
            </button>
          )}

          {/* Toggle Report Access */}
          {showToggleReport && (
            <button
              className={styles.actionBtnView}
              onClick={() => onToggleReport(row)}
              title="Toggle report download access"
              disabled={isLoading}
              style={{
                background: "#ede9fe",
                borderColor: "#c4b5fd",
                color: "#6d28d9",
              }}
            >
              <FiFileText size={14} />
            </button>
          )}
        </div>
      </td>
    </tr>
  );
}
