import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import api from "../api/client";
import { useAuth } from "../auth/AuthContext";
import ConfirmDialog from "../components/ConfirmDialog";

const ROLE_COLORS = {
  sysadmin: { bg: "var(--danger-bg)", text: "var(--danger-text)" },
  admin:    { bg: "#3b2a0a",          text: "#f6ad55"            },
  editor:   { bg: "var(--badge-blue-bg)", text: "var(--badge-blue-text)" },
  user:     { bg: "var(--bg-card-hover)", text: "var(--text-muted)"      },
};

function Field({ label, children }) {
  return (
    <div>
      <dt className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>{label}</dt>
      <dd className="mt-1 text-sm" style={{ color: "var(--text-primary)" }}>{children || "-"}</dd>
    </div>
  );
}

/** Yes/No badge */
function PBadge({ value }) {
  return value ? (
    <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>Yes</span>
  ) : (
    <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }}>No</span>
  );
}

/** Access level badge for segmented permissions */
function LevelBadge({ viewVal, editVal }) {
  if (editVal) return <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}>Edit</span>;
  if (viewVal) return <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: "var(--success-bg)", color: "var(--success-text)" }}>View Only</span>;
  return <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }}>No Access</span>;
}

/** A row in the permission display */
function PermRow({ label, value }) {
  return (
    <div className="flex items-center justify-between py-1.5" style={{ borderBottom: "1px solid var(--border-secondary)" }}>
      <span className="text-sm" style={{ color: "var(--text-primary)" }}>{label}</span>
      <PBadge value={value} />
    </div>
  );
}

/** A segmented row in the permission display */
function SegmentedRow({ label, viewVal, editVal }) {
  return (
    <div className="flex items-center justify-between py-1.5" style={{ borderBottom: "1px solid var(--border-secondary)" }}>
      <span className="text-sm" style={{ color: "var(--text-primary)" }}>{label}</span>
      <LevelBadge viewVal={viewVal} editVal={editVal} />
    </div>
  );
}

/** Section card for permissions display */
function PermSection({ title, children }) {
  return (
    <section className="ui-section-card">
      <h2 className="ui-section-card__title-row">
        <span className="ui-section-card__title">{title}</span>
      </h2>
      <div className="pt-2">
        {children}
      </div>
    </section>
  );
}

export default function StaffDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user } = useAuth();

  const [member, setMember] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showDelete, setShowDelete] = useState(false);
  const [showResetPw, setShowResetPw] = useState(false);
  const [newPassword, setNewPassword] = useState("");
  const [pwError, setPwError] = useState("");
  const [pwSuccess, setPwSuccess] = useState("");

  useEffect(() => {
    loadStaff();
  }, [id]);

  const loadStaff = async () => {
    setLoading(true);
    try {
      const data = await api.get(`/staff/${id}`);
      setMember(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    try {
      await api.delete(`/staff/${id}`);
      navigate("/settings/staff");
    } catch (err) {
      setError(err.message);
      setShowDelete(false);
    }
  };

  const handleResetPassword = async () => {
    setPwError("");
    setPwSuccess("");
    if (newPassword.length < 6) {
      setPwError("Password must be at least 6 characters");
      return;
    }
    try {
      await api.put(`/staff/${id}/password`, { new_password: newPassword });
      setPwSuccess("Password updated successfully");
      setNewPassword("");
      setTimeout(() => {
        setShowResetPw(false);
        setPwSuccess("");
      }, 2000);
    } catch (err) {
      setPwError(err.message);
    }
  };

  if (loading) return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
  if (error) return (
    <div className="text-sm rounded-md p-3 border" style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}>
      {error}
    </div>
  );
  if (!member) return null;

  const canEdit = !(user?.role === "admin" && member.role === "sysadmin");
  const canDelete = canEdit && member.id !== user?.sub;
  const roleColors = ROLE_COLORS[member.role] || ROLE_COLORS.user;

  const showPerms = (member.role === "editor" || member.role === "user") && member.permissions;
  const q = member.permissions || {};

  const mel   = q.melodies      || {};
  const dev   = q.devices        || {};
  const usr   = q.app_users      || {};
  const iss   = q.issues_notes   || {};
  const mail  = q.mail           || {};
  const crm   = q.crm            || {};
  const cc    = q.crm_customers  || {};
  const cprod = q.crm_products   || {};
  const mfg   = q.mfg            || {};
  const apir  = q.api_reference  || {};
  const mqtt  = q.mqtt           || {};

  return (
    <div>
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <button onClick={() => navigate("/settings/staff")} className="text-sm hover:underline mb-2 inline-block" style={{ color: "var(--accent)" }}>
            &larr; Back to Staff
          </button>
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>{member.name}</h1>
            <span className="px-2 py-0.5 text-xs rounded-full capitalize" style={{ backgroundColor: roleColors.bg, color: roleColors.text }}>
              {member.role}
            </span>
            <span
              className="px-2 py-0.5 text-xs rounded-full"
              style={member.is_active
                ? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
                : { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}
            >
              {member.is_active ? "Active" : "Inactive"}
            </span>
          </div>
        </div>
        {canEdit && (
          <div className="flex gap-2">
            <button onClick={() => navigate(`/settings/staff/${id}/edit`)} className="px-4 py-2 text-sm rounded-md transition-colors" style={{ backgroundColor: "var(--text-link)", color: "var(--text-white)" }}>
              Edit
            </button>
            <button onClick={() => setShowResetPw(true)} className="px-4 py-2 text-sm rounded-md transition-colors border" style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)" }}>
              Reset Password
            </button>
            {canDelete && (
              <button onClick={() => setShowDelete(true)} className="px-4 py-2 text-sm rounded-md transition-colors" style={{ backgroundColor: "var(--danger)", color: "var(--text-white)" }}>
                Delete
              </button>
            )}
          </div>
        )}
      </div>

      {/* Account Info — full width */}
      <section className="ui-section-card mb-6">
        <h2 className="ui-section-card__header-title mb-4">Account Information</h2>
        <dl className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <Field label="Name">{member.name}</Field>
          <Field label="Email">{member.email}</Field>
          <Field label="Role">
            <span className="px-2 py-0.5 text-xs rounded-full capitalize" style={{ backgroundColor: roleColors.bg, color: roleColors.text }}>
              {member.role}
            </span>
          </Field>
          <Field label="Status">
            <span
              className="px-2 py-0.5 text-xs rounded-full"
              style={member.is_active
                ? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
                : { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }}
            >
              {member.is_active ? "Active" : "Inactive"}
            </span>
          </Field>
          <Field label="Document ID">
            <span className="font-mono text-xs" style={{ color: "var(--text-muted)" }}>{member.id}</span>
          </Field>
        </dl>
      </section>

      {/* Admin / SysAdmin notice */}
      {(member.role === "sysadmin" || member.role === "admin") && (
        <section className="ui-section-card">
          <h2 className="ui-section-card__header-title mb-3">Permissions</h2>
          <p className="text-sm" style={{ color: "var(--text-muted)" }}>
            {member.role === "sysadmin"
              ? "SysAdmin has full god-mode access to all features and settings."
              : "Admin has full access to all features, except managing SysAdmin accounts and system-level settings."}
          </p>
        </section>
      )}

      {/* Permission sections */}
      {showPerms && (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">

            {/* Melodies */}
            <PermSection title="Melodies">
              <PermRow label="View"             value={mel.view} />
              <PermRow label="Add"              value={mel.add} />
              <PermRow label="Delete"           value={mel.delete} />
              <PermRow label="Safe Edit"        value={mel.safe_edit || mel.full_edit} />
              <PermRow label="Full Edit"        value={mel.full_edit} />
              <PermRow label="Archetype Access" value={mel.archetype_access} />
              <PermRow label="Settings Access"  value={mel.settings_access} />
              <PermRow label="Compose Access"   value={mel.compose_access} />
            </PermSection>

            {/* Devices */}
            <PermSection title="Devices">
              <PermRow label="View"              value={dev.view} />
              <PermRow label="Add"               value={dev.add} />
              <PermRow label="Delete"            value={dev.delete} />
              <PermRow label="Safe Edit (Info)"  value={dev.safe_edit || dev.full_edit} />
              <PermRow label="Edit Bells"        value={dev.edit_bells || dev.full_edit} />
              <PermRow label="Edit Clock & Alerts" value={dev.edit_clock || dev.full_edit} />
              <PermRow label="Edit Warranty/Sub" value={dev.edit_warranty || dev.full_edit} />
              <PermRow label="Full Edit"         value={dev.full_edit} />
              <PermRow label="Control"           value={dev.control} />
            </PermSection>

            {/* App Users */}
            <PermSection title="App Users">
              <PermRow label="View"      value={usr.view} />
              <PermRow label="Add"       value={usr.add} />
              <PermRow label="Delete"    value={usr.delete} />
              <PermRow label="Safe Edit" value={usr.safe_edit || usr.full_edit} />
              <PermRow label="Full Edit" value={usr.full_edit} />
            </PermSection>

            {/* Issues & Notes */}
            <PermSection title="Issues & Notes">
              <PermRow label="View"   value={iss.view} />
              <PermRow label="Add"    value={iss.add} />
              <PermRow label="Delete" value={iss.delete} />
              <PermRow label="Edit"   value={iss.edit} />
            </PermSection>

            {/* Mail */}
            <PermSection title="Mail">
              <PermRow label="View Inbox" value={mail.view} />
              <PermRow label="Compose"    value={mail.compose} />
              <PermRow label="Reply"      value={mail.reply} />
            </PermSection>

            {/* CRM */}
            <PermSection title="CRM">
              <PermRow label="View Activity Log" value={crm.activity_log} />
            </PermSection>

            {/* CRM Products */}
            <PermSection title="CRM Products">
              <PermRow label="View"        value={cprod.view} />
              <PermRow label="Add"         value={cprod.add} />
              <PermRow label="Edit/Delete" value={cprod.edit} />
            </PermSection>

            {/* Manufacturing */}
            <PermSection title="Manufacturing">
              <PermRow label="View Inventory"   value={mfg.view_inventory} />
              <PermRow label="Edit"             value={mfg.edit} />
              <PermRow label="Provision Device" value={mfg.provision} />
              <SegmentedRow label="Firmware"    viewVal={mfg.firmware_view} editVal={mfg.firmware_edit} />
            </PermSection>

          </div>

          {/* CRM Customers — full width */}
          <section className="ui-section-card mt-6">
            <h2 className="ui-section-card__title-row">
              <span className="ui-section-card__title">CRM Customers</span>
              {cc.full_access && (
                <span className="text-xs px-2 py-0.5 rounded ml-3" style={{ backgroundColor: "rgba(116,184,22,0.15)", color: "var(--accent)" }}>
                  Full Access
                </span>
              )}
            </h2>
            <div className="pt-2 grid grid-cols-1 md:grid-cols-2 gap-x-8">
              <div>
                <PermRow label="Overview Tab"     value={cc.full_access || cc.overview} />
                <PermRow label="Add Customer"     value={cc.full_access || cc.add} />
                <PermRow label="Delete Customer"  value={cc.full_access || cc.delete} />
                <SegmentedRow label="Orders"      viewVal={cc.full_access || cc.orders_view} editVal={cc.full_access || cc.orders_edit} />
                <SegmentedRow label="Quotations"  viewVal={cc.full_access || cc.quotations_view} editVal={cc.full_access || cc.quotations_edit} />
              </div>
              <div>
                <SegmentedRow label="Files & Media" viewVal={cc.full_access || cc.files_view} editVal={cc.full_access || cc.files_edit} />
                <SegmentedRow label="Devices Tab"   viewVal={cc.full_access || cc.devices_view} editVal={cc.full_access || cc.devices_edit} />
                <PermRow label="Comms: View"         value={cc.full_access || cc.comms_view} />
                <PermRow label="Comms: Log Entry"    value={cc.full_access || cc.comms_log} />
                <PermRow label="Comms: Edit Entries" value={cc.full_access || cc.comms_edit} />
                <PermRow label="Comms: Compose & Send" value={cc.full_access || cc.comms_compose} />
              </div>
            </div>
          </section>

          {/* API Reference + MQTT */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
            <PermSection title="API Reference">
              <PermRow label="Access API Reference" value={apir.access} />
            </PermSection>
            <PermSection title="MQTT">
              <PermRow label="MQTT Access" value={mqtt.access} />
            </PermSection>
          </div>
        </>
      )}

      {/* Reset Password Dialog */}
      {showResetPw && (
        <div className="fixed inset-0 z-50 flex items-center justify-center" style={{ backgroundColor: "rgba(0,0,0,0.5)" }}>
          <div className="rounded-lg border p-6 w-full max-w-md" style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}>
            <h3 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>Reset Password</h3>
            <p className="text-sm mb-4" style={{ color: "var(--text-muted)" }}>Enter a new password for {member.name}.</p>
            <input
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              placeholder="New password"
              className="w-full px-3 py-2 rounded-md text-sm border mb-3"
              style={{ backgroundColor: "var(--bg-input)", color: "var(--text-primary)", borderColor: "var(--border-primary)" }}
            />
            {pwError   && <p className="text-xs mb-2" style={{ color: "var(--danger-text)" }}>{pwError}</p>}
            {pwSuccess && <p className="text-xs mb-2" style={{ color: "var(--success-text)" }}>{pwSuccess}</p>}
            <div className="flex gap-2 justify-end">
              <button
                onClick={() => { setShowResetPw(false); setNewPassword(""); setPwError(""); setPwSuccess(""); }}
                className="px-4 py-2 text-sm rounded-md border cursor-pointer"
                style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)" }}
              >
                Cancel
              </button>
              <button
                onClick={handleResetPassword}
                className="px-4 py-2 text-sm rounded-md cursor-pointer"
                style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
              >
                Update Password
              </button>
            </div>
          </div>
        </div>
      )}

      <ConfirmDialog
        open={showDelete}
        title="Delete Staff Member"
        message={`Are you sure you want to delete "${member.name}" (${member.email})? This action cannot be undone.`}
        onConfirm={handleDelete}
        onCancel={() => setShowDelete(false)}
      />
    </div>
  );
}
