"use client";

import React from "react";
import styles from "../../modules/commonstyle/dattabale.module.css";
import {
  FiChevronRight, FiUser, FiMail, FiCalendar,
  FiEdit, FiTrash2, FiEye, FiCheckCircle,
  FiXCircle, FiKey, FiShield,
} from "react-icons/fi";
import { UserRowProps } from "@/lib/api/types/user.types";
import {
  getUserStatus,
  formatUserDate,
  getUserInitials,
  getUserAvatarColor,
} from "@/lib/api/mappers/user.mapper";

function StatusBadge({ user }: { user: UserRowProps["row"] }) {
  const { label, color, bg } = getUserStatus(user);
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 5,
      padding: "3px 10px", borderRadius: 20,
      fontSize: 10, fontWeight: 700, letterSpacing: "0.3px",
      background: bg, color,
    }}>
      <span style={{ width: 5, height: 5, borderRadius: "50%", background: color }} />
      {label}
    </span>
  );
}

export const UserRow = ({
  row, isExpanded, isSelected,
  toggleRowExpand, handleRowSelect,
  onEdit, onDelete, onApprove, onReject, onManageRoles,
  onVerify, // ✅ added
}: UserRowProps) => {
  const isPendingApproval =
    row.isEmailVerified && !row.isApprovedByAdmin && row.status !== "rejected";
  const isUnverified = !row.isEmailVerified; // ✅ added

  return (
    <>
      <tr className={`${styles.tableRow} ${isSelected ? styles.selectedRow : ""}`}>

        <td className={styles.expandCell}>
          <button className={styles.expandBtn} onClick={() => toggleRowExpand(row.sno)} aria-label={isExpanded ? "Collapse" : "Expand"}>
            <FiChevronRight size={16} className={`${styles.expandIcon} ${isExpanded ? styles.expanded : ""}`} />
          </button>
        </td>

        <td style={{ textAlign: "center", padding: "10px 8px" }}>
          <input type="checkbox" className={styles.checkbox} checked={isSelected} onChange={(e) => handleRowSelect(row.sno, e.target.checked)} />
        </td>

        <td className={styles.idCell}>{row.sno}</td>

        <td className={styles.nameCell}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ width: 32, height: 32, borderRadius: "50%", flexShrink: 0, background: getUserAvatarColor(row.id), color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700 }}>
              {getUserInitials(row)}
            </div>
            <div>
              <div style={{ fontWeight: 600, fontSize: 13, color: "#111827" }}>{row.firstName} {row.lastName}</div>
              <div style={{ fontSize: 10, color: "#9ca3af" }}>ID #{row.id}</div>
            </div>
          </div>
        </td>

        <td style={{ fontSize: 12, color: "#6b7280" }}>{row.email}</td>

        <td>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
            {row.roles.length === 0 ? (
              <span style={{ color: "#d1d5db", fontSize: 11, fontStyle: "italic" }}>No role</span>
            ) : (
              row.roles.map((r) => <span key={r.id} className={styles.departmentTag}>{r.name}</span>)
            )}
          </div>
        </td>

        <td><StatusBadge user={row} /></td>

        <td style={{ fontSize: 11, color: "#9ca3af", whiteSpace: "nowrap" }}>
          {formatUserDate(row.created_at)}
        </td>

        <td className={styles.actionsCell}>
          <div className={styles.actionGroup}>
            <button className={styles.actionBtnView} onClick={() => toggleRowExpand(row.sno)} title="View">
              <FiEye size={14} />
            </button>
            <button className={styles.actionBtnEdit} onClick={() => onManageRoles(row.id)} title="Manage Roles">
              <FiKey size={14} />
            </button>

            {/* ✅ ADDED — Verify button (shows only for unverified users) */}
            {isUnverified && (
              <button
                onClick={() => onVerify(row.id)}
                title="Verify Email"
                style={{ padding: "5px 8px", borderRadius: 6, border: "none", background: "#eff6ff", color: "#2563eb", cursor: "pointer" }}
              >
                <FiCheckCircle size={14} />
              </button>
            )}

            {isPendingApproval && (
              <>
                <button onClick={() => onApprove(row.id)} title="Approve User" style={{ padding: "5px 8px", borderRadius: 6, border: "none", background: "#dcfce7", color: "#16a34a", cursor: "pointer" }}>
                  <FiCheckCircle size={14} />
                </button>
                <button onClick={() => onReject(row.id)} title="Reject User" style={{ padding: "5px 8px", borderRadius: 6, border: "none", background: "#fee2e2", color: "#dc2626", cursor: "pointer" }}>
                  <FiXCircle size={14} />
                </button>
              </>
            )}
            <button className={styles.actionBtnEdit} onClick={() => onEdit(row.id)} title="Edit">
              <FiEdit size={14} />
            </button>
            <button className={styles.actionBtnDelete} onClick={() => onDelete(row.id)} title="Delete">
              <FiTrash2 size={14} />
            </button>
          </div>
        </td>
      </tr>

      {isExpanded && (
        <tr className={styles.expandedRow}>
          <td colSpan={9}>
            <div className={styles.expandedContent}>
              <div className={styles.detailPanel}>
                <div className={styles.panelHeader}>User Details</div>

                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Personal Information</div>
                  <div className={styles.definitionGrid}>
                    <div className={styles.definitionItem}>
                      <FiUser size={16} /><span className={styles.label}>First Name</span><span className={styles.value}>{row.firstName}</span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiUser size={16} /><span className={styles.label}>Last Name</span><span className={styles.value}>{row.lastName}</span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiMail size={16} /><span className={styles.label}>Email</span><span className={styles.value}>{row.email}</span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiCheckCircle size={16} /><span className={styles.label}>Status</span><span className={styles.value}><StatusBadge user={row} /></span>
                    </div>
                  </div>
                </div>

                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Roles &amp; Permissions</div>
                  <div className={styles.definitionGrid}>
                    <div className={`${styles.definitionItem} ${styles.fullRow}`}>
                      <FiShield size={16} />
                      <span className={styles.label}>Assigned Roles</span>
                      <span className={styles.value}>
                        {row.roles.length === 0 ? (
                          <span style={{ color: "#9ca3af", fontStyle: "italic" }}>No roles assigned</span>
                        ) : (
                          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                            {row.roles.map((r) => <span key={r.id} className={styles.departmentTag}>{r.name}</span>)}
                          </div>
                        )}
                      </span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiKey size={16} /><span className={styles.label}>Direct Permissions</span><span className={styles.value}>{row.permissions.length} assigned</span>
                    </div>
                  </div>
                </div>

                <div className={styles.panelSection}>
                  <div className={styles.sectionTitleText}>Account Info</div>
                  <div className={styles.definitionGrid}>
                    <div className={styles.definitionItem}>
                      <FiCheckCircle size={16} /><span className={styles.label}>Email Verified</span>
                      <span className={styles.value}>{row.isEmailVerified ? "✅ Yes" : "❌ No"}</span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiShield size={16} /><span className={styles.label}>Admin Approved</span>
                      <span className={styles.value}>{row.isApprovedByAdmin ? "✅ Yes" : "❌ No"}</span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiCalendar size={16} /><span className={styles.label}>Joined</span><span className={styles.value}>{formatUserDate(row.created_at)}</span>
                    </div>
                    <div className={styles.definitionItem}>
                      <FiCalendar size={16} /><span className={styles.label}>Last Updated</span><span className={styles.value}>{formatUserDate(row.updated_at)}</span>
                    </div>
                  </div>
                </div>

                <div className={styles.panelActions}>
                  <button className={styles.primaryBtn} onClick={() => onManageRoles(row.id)}>
                    <FiKey size={16} /> Manage Roles
                  </button>
                  <button className={styles.secondaryBtn} onClick={() => onEdit(row.id)}>
                    <FiEdit size={16} /> Edit User
                  </button>

                  {/* ✅ ADDED — Verify button in expanded panel */}
                  {isUnverified && (
                    <button
                      onClick={() => onVerify(row.id)}
                      style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 16px", borderRadius: 8, border: "none", background: "#eff6ff", color: "#2563eb", fontWeight: 600, fontSize: 13, cursor: "pointer" }}
                    >
                      <FiCheckCircle size={16} /> Verify Email
                    </button>
                  )}

                  {isPendingApproval && (
                    <button
                      onClick={() => onApprove(row.id)}
                      style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 16px", borderRadius: 8, border: "none", background: "#dcfce7", color: "#16a34a", fontWeight: 600, fontSize: 13, cursor: "pointer" }}
                    >
                      <FiCheckCircle size={16} /> Approve
                    </button>
                  )}
                  <button className={styles.dangerBtn} onClick={() => onDelete(row.id)}>
                    <FiTrash2 size={16} /> Delete
                  </button>
                </div>
              </div>
            </div>
          </td>
        </tr>
      )}
    </>
  );
};