"use client";

import { useState, useEffect } from "react";
import toast from "react-hot-toast";
import { RoleFormProps } from "@/lib/api/types/user.types";
import { assignUserRoles } from "@/lib/api/user.api";
import { getUserInitials, getUserAvatarColor } from "@/lib/api/mappers/user.mapper";

export default function RoleForm({ isOpen, onClose, refreshData, user, roles }: RoleFormProps) {
  const [selectedRoleIds, setSelectedRoleIds] = useState<number[]>([]);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (user) {
      setSelectedRoleIds((user.roles || []).map((r) => r.id));
    }
  }, [user]);

  const toggleRole = (id: number) =>
    setSelectedRoleIds((prev) =>
      prev.includes(id) ? prev.filter((r) => r !== id) : [...prev, id]
    );

  const handleSave = async () => {
    if (!user) return;
    setSaving(true);
    try {
      await assignUserRoles(user.id, { roleIds: selectedRoleIds });
      toast.success("Roles updated successfully!");
      onClose();
      refreshData?.();
    } catch (err: any) {
      toast.error(err.message || "Failed to assign roles");
    } finally {
      setSaving(false);
    }
  };

  if (!isOpen || !user) return null;

  return (
    <div
      style={{
        position: "fixed", inset: 0,
        background: "rgba(0,0,0,0.55)", backdropFilter: "blur(4px)",
        zIndex: 9999, display: "flex", alignItems: "center",
        justifyContent: "center", padding: 20,
      }}
      onClick={onClose}
    >
      <div
        style={{
          background: "#fff", borderRadius: 18, width: "100%",
          maxWidth: 500, maxHeight: "90vh", overflowY: "auto",
          boxShadow: "0 24px 64px rgba(0,0,0,0.18)",
        }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div style={{
          padding: "20px 22px 16px", borderBottom: "1px solid #f3f4f6",
          display: "flex", alignItems: "center", justifyContent: "space-between",
          background: "linear-gradient(135deg,rgba(139,20,212,0.04),rgba(121,4,194,0.06))",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{
              width: 36, height: 36, borderRadius: "50%", flexShrink: 0,
              background: getUserAvatarColor(user.id), color: "#fff",
              display: "flex", alignItems: "center", justifyContent: "center",
              fontSize: 13, fontWeight: 700,
            }}>
              {getUserInitials(user)}
            </div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 700, color: "#111827" }}>
                Assign Roles
              </div>
              <div style={{ fontSize: 12, color: "#9ca3af" }}>
                {user.firstName} {user.lastName} — {user.email}
              </div>
            </div>
          </div>
          <button onClick={onClose} style={{
            background: "none", border: "none", fontSize: 22,
            cursor: "pointer", color: "#9ca3af", padding: "4px 8px", borderRadius: 8,
          }}>×</button>
        </div>

        {/* Body */}
        <div style={{ padding: "20px 22px" }}>
          <p style={{ fontSize: 13, color: "#6b7280", marginBottom: 16 }}>
            Select roles to assign to this user:
          </p>

          {roles.length === 0 ? (
            <p style={{ color: "#9ca3af", fontSize: 13, fontStyle: "italic" }}>
              No roles found. Create roles in the Roles &amp; Permissions tab.
            </p>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(200px,1fr))", gap: 10 }}>
              {roles.map((role) => {
                const selected = selectedRoleIds.includes(role.id);
                return (
                  <div
                    key={role.id}
                    onClick={() => toggleRole(role.id)}
                    style={{
                      padding: "12px 14px", borderRadius: 12, cursor: "pointer",
                      border: selected ? "2px solid #8b14d4" : "2px solid #e5e7eb",
                      background: selected ? "rgba(139,20,212,0.06)" : "#fafafa",
                      transition: "all 0.15s", position: "relative",
                    }}
                  >
                    {/* Checkmark */}
                    <div style={{
                      position: "absolute", top: 10, right: 10,
                      width: 18, height: 18, borderRadius: "50%",
                      border: selected ? "2px solid #8b14d4" : "2px solid #e5e7eb",
                      background: selected ? "#8b14d4" : "#fff",
                      display: "flex", alignItems: "center", justifyContent: "center",
                    }}>
                      {selected && (
                        <svg width="10" height="8" viewBox="0 0 10 8" fill="none">
                          <path d="M1 4L3.5 6.5L9 1" stroke="white" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                      )}
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 700, color: "#111827", marginRight: 24 }}>
                      {role.name}
                    </div>
                    {role.description && (
                      <div style={{ fontSize: 11, color: "#9ca3af", marginTop: 3 }}>
                        {role.description}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={{
          padding: "14px 22px", borderTop: "1px solid #f3f4f6",
          display: "flex", gap: 8, justifyContent: "flex-end",
        }}>
          <button onClick={onClose} style={{
            padding: "9px 18px", borderRadius: 9, border: "1px solid #e5e7eb",
            background: "#fff", color: "#6b7280", fontSize: 13, fontWeight: 600, cursor: "pointer",
          }}>
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={saving}
            style={{
              padding: "9px 20px", borderRadius: 9, border: "none",
              background: "linear-gradient(135deg,#8b14d4,#6d0fa6)",
              color: "#fff", fontSize: 13, fontWeight: 700,
              cursor: saving ? "not-allowed" : "pointer",
              opacity: saving ? 0.6 : 1,
              boxShadow: "0 4px 12px rgba(139,20,212,0.25)",
            }}
          >
            {saving ? "Saving..." : `Assign ${selectedRoleIds.length} Role(s)`}
          </button>
        </div>
      </div>
    </div>
  );
}
