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

function Field({ label, children }) {
  return (
    <div>
      <dt className="ui-field-label">{label}</dt>
      <dd className="mt-1 text-sm" style={{ color: "var(--text-primary)" }}>
        {children || "-"}
      </dd>
    </div>
  );
}

export default function UserDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("app_users", "edit");

  const [user, setUser] = useState(null);
  const [devices, setDevices] = useState([]);
  const [allDevices, setAllDevices] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showDelete, setShowDelete] = useState(false);
  const [blocking, setBlocking] = useState(false);
  const [assigningDevice, setAssigningDevice] = useState(false);
  const [selectedDeviceId, setSelectedDeviceId] = useState("");
  const [showAssignPanel, setShowAssignPanel] = useState(false);
  const [uploadingPhoto, setUploadingPhoto] = useState(false);
  const photoInputRef = useRef(null);

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

  const loadData = async () => {
    setLoading(true);
    try {
      const [u, d] = await Promise.all([
        api.get(`/users/${id}`),
        api.get(`/users/${id}/devices`),
      ]);
      setUser(u);
      setDevices(d);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const loadAllDevices = async () => {
    try {
      const data = await api.get("/devices");
      setAllDevices(data.devices || []);
    } catch (err) {
      setError(err.message);
    }
  };

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

  const handleBlockToggle = async () => {
    setBlocking(true);
    setError("");
    try {
      const endpoint = user.status === "blocked"
        ? `/users/${id}/unblock`
        : `/users/${id}/block`;
      const updated = await api.post(endpoint);
      setUser(updated);
    } catch (err) {
      setError(err.message);
    } finally {
      setBlocking(false);
    }
  };

  const handleAssignDevice = async () => {
    if (!selectedDeviceId) return;
    setAssigningDevice(true);
    setError("");
    try {
      await api.post(`/users/${id}/devices/${selectedDeviceId}`);
      setSelectedDeviceId("");
      setShowAssignPanel(false);
      const d = await api.get(`/users/${id}/devices`);
      setDevices(d);
    } catch (err) {
      setError(err.message);
    } finally {
      setAssigningDevice(false);
    }
  };

  const handleUnassignDevice = async (deviceId) => {
    setError("");
    try {
      await api.delete(`/users/${id}/devices/${deviceId}`);
      const d = await api.get(`/users/${id}/devices`);
      setDevices(d);
    } catch (err) {
      setError(err.message);
    }
  };

  const openAssignPanel = () => {
    setShowAssignPanel(true);
    loadAllDevices();
  };

  const handlePhotoUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploadingPhoto(true);
    setError("");
    try {
      const result = await api.upload(`/users/${id}/photo`, file);
      setUser((prev) => ({ ...prev, photo_url: result.photo_url }));
    } catch (err) {
      setError(err.message);
    } finally {
      setUploadingPhoto(false);
      if (photoInputRef.current) photoInputRef.current.value = "";
    }
  };

  if (loading) {
    return (
      <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>
        Loading...
      </div>
    );
  }

  if (error && !user) {
    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 (!user) return null;

  const isBlocked = user.status === "blocked";

  const assignedDeviceIds = new Set(devices.map((d) => d.id));
  const availableDevices = allDevices.filter((d) => !assignedDeviceIds.has(d.id));

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <button
            onClick={() => navigate("/users")}
            className="text-sm hover:underline mb-2 inline-block"
            style={{ color: "var(--accent)" }}
          >
            &larr; Back to App Users
          </button>
          <div className="flex items-center gap-3">
            <h1
              className="text-2xl font-bold"
              style={{ color: "var(--text-heading)" }}
            >
              {user.display_name || "Unnamed User"}
            </h1>
            <span
              className="px-2 py-0.5 text-xs rounded-full"
              style={
                isBlocked
                  ? { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }
                  : user.status === "active"
                  ? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
                  : { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }
              }
            >
              {user.status || "unknown"}
            </span>
          </div>
        </div>
        {canEdit && (
          <div className="flex gap-2">
            <button
              onClick={handleBlockToggle}
              disabled={blocking}
              className="px-4 py-2 text-sm rounded-md transition-colors disabled:opacity-50"
              style={
                isBlocked
                  ? { backgroundColor: "var(--success)", color: "var(--text-white)" }
                  : { backgroundColor: "var(--warning, #f59e0b)", color: "var(--text-white)" }
              }
            >
              {blocking ? "..." : isBlocked ? "Unblock" : "Block"}
            </button>
            <button
              onClick={() => navigate(`/users/${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={() => 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>

      {error && (
        <div
          className="text-sm rounded-md p-3 mb-4 border"
          style={{
            backgroundColor: "var(--danger-bg)",
            borderColor: "var(--danger)",
            color: "var(--danger-text)",
          }}
        >
          {error}
        </div>
      )}

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
        {/* Left column */}
        <div className="space-y-6">
          {/* Account Info */}
          <section className="ui-section-card">
            <div className="ui-section-card__title-row">
              <h2 className="ui-section-card__header-title">Account Information</h2>
            </div>
            <div style={{ display: "flex", gap: "1.5rem" }}>
              {/* Profile Photo */}
              <div className="shrink-0" style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "0.5rem" }}>
                <div
                  className="relative rounded-full overflow-hidden"
                  style={{ width: 80, height: 80, backgroundColor: "var(--bg-card-hover)" }}
                >
                  {user.photo_url ? (
                    <img
                      src={user.photo_url}
                      alt={user.display_name || "User"}
                      style={{ width: "100%", height: "100%", objectFit: "cover" }}
                    />
                  ) : (
                    <div
                      className="w-full h-full flex items-center justify-center text-2xl font-bold"
                      style={{ color: "var(--text-muted)" }}
                    >
                      {(user.display_name || user.email || "?").charAt(0).toUpperCase()}
                    </div>
                  )}
                </div>
                {canEdit && (
                  <>
                    <button
                      onClick={() => photoInputRef.current?.click()}
                      disabled={uploadingPhoto}
                      className="text-xs hover:opacity-80 cursor-pointer transition-colors"
                      style={{ color: "var(--text-link)" }}
                    >
                      {uploadingPhoto ? "Uploading..." : "Change Photo"}
                    </button>
                    <input
                      ref={photoInputRef}
                      type="file"
                      accept="image/*"
                      onChange={handlePhotoUpload}
                      style={{ display: "none" }}
                    />
                  </>
                )}
              </div>
              {/* Fields */}
              <dl className="grid grid-cols-2 md:grid-cols-3 gap-4 flex-1">
                <Field label="Title">{user.userTitle}</Field>
                <Field label="Phone">{user.phone_number}</Field>
                <Field label="UID">
                  <span className="font-mono text-xs" style={{ color: "var(--text-muted)" }}>
                    {user.uid || user.id}
                  </span>
                </Field>
                <Field label="Email">{user.email}</Field>
                <Field label="Status">
                  <span
                    className="px-2 py-0.5 text-xs rounded-full"
                    style={
                      isBlocked
                        ? { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }
                        : user.status === "active"
                        ? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
                        : { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }
                    }
                  >
                    {user.status || "unknown"}
                  </span>
                </Field>
              </dl>
            </div>
          </section>

          {/* Profile */}
          <section className="ui-section-card">
            <div className="ui-section-card__title-row">
              <h2 className="ui-section-card__header-title">Profile</h2>
            </div>
            <dl className="grid grid-cols-1 gap-4">
              <Field label="Bio">{user.bio}</Field>
            </dl>
          </section>

          {/* Timestamps */}
          <section className="ui-section-card">
            <div className="ui-section-card__title-row">
              <h2 className="ui-section-card__header-title">Activity</h2>
            </div>
            <dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <Field label="Created Time">{user.created_time}</Field>
              <Field label="Created At">{user.createdAt}</Field>
              <Field label="Last Active">{user.lastActive}</Field>
            </dl>
          </section>
        </div>

        {/* Right column */}
        <div className="space-y-6">
          {/* Security */}
          <section className="ui-section-card">
            <div className="ui-section-card__title-row">
              <h2 className="ui-section-card__header-title">Security</h2>
            </div>
            <dl className="grid grid-cols-2 gap-4">
              <Field label="Settings PIN">{user.settingsPIN ? "****" : "-"}</Field>
              <Field label="Quick Settings PIN">{user.quickSettingsPIN ? "****" : "-"}</Field>
            </dl>
          </section>

          {/* Friends */}
          <section className="ui-section-card">
            <div className="ui-section-card__title-row">
              <h2 className="ui-section-card__header-title">Friends</h2>
            </div>
            <dl className="grid grid-cols-2 gap-4">
              <Field label="Friends">
                {user.friendsList?.length ?? 0}
              </Field>
              <Field label="Friends Invited">
                {user.friendsInvited?.length ?? 0}
              </Field>
            </dl>
          </section>

          {/* Assigned Devices */}
          <section className="ui-section-card">
            <div className="ui-section-card__title-row">
              <h2 className="ui-section-card__header-title">Assigned Devices ({devices.length})</h2>
              {canEdit && (
                <button
                  onClick={openAssignPanel}
                  className="px-3 py-1.5 text-xs rounded-md hover:opacity-90 transition-colors cursor-pointer"
                  style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
                >
                  Assign Device
                </button>
              )}
            </div>

            {showAssignPanel && (
              <div
                className="mb-4 p-3 rounded-md border"
                style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-primary)" }}
              >
                <div className="flex gap-2 items-end">
                  <div className="flex-1">
                    <label className="block text-xs font-medium mb-1" style={{ color: "var(--text-secondary)" }}>
                      Select Device
                    </label>
                    <select
                      value={selectedDeviceId}
                      onChange={(e) => setSelectedDeviceId(e.target.value)}
                      className="w-full px-3 py-2 rounded-md text-sm border"
                      style={{
                        backgroundColor: "var(--bg-card)",
                        color: "var(--text-primary)",
                        borderColor: "var(--border-primary)",
                      }}
                    >
                      <option value="">Choose a device...</option>
                      {availableDevices.map((d) => (
                        <option key={d.id} value={d.id}>
                          {d.device_name || "Unnamed"} ({d.device_id || d.id})
                        </option>
                      ))}
                    </select>
                  </div>
                  <button
                    onClick={handleAssignDevice}
                    disabled={!selectedDeviceId || assigningDevice}
                    className="px-3 py-2 text-sm rounded-md hover:opacity-90 disabled:opacity-50 transition-colors"
                    style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
                  >
                    {assigningDevice ? "..." : "Assign"}
                  </button>
                  <button
                    onClick={() => { setShowAssignPanel(false); setSelectedDeviceId(""); }}
                    className="px-3 py-2 text-sm rounded-md hover:opacity-80 transition-colors"
                    style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-primary)" }}
                  >
                    Cancel
                  </button>
                </div>
              </div>
            )}

            {devices.length === 0 ? (
              <p className="text-sm" style={{ color: "var(--text-muted)" }}>
                No devices assigned.
              </p>
            ) : (
              <div className="space-y-2">
                {devices.map((device) => (
                  <div
                    key={device.id}
                    className="flex items-center justify-between p-3 rounded-md border"
                    style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-primary)" }}
                  >
                    <div className="flex items-center gap-3">
                      <span
                        className={`inline-block w-2.5 h-2.5 rounded-full ${
                          device.is_Online ? "bg-green-500" : ""
                        }`}
                        style={!device.is_Online ? { backgroundColor: "var(--border-primary)" } : undefined}
                        title={device.is_Online ? "Online" : "Offline"}
                      />
                      <div>
                        <button
                          onClick={() => navigate(`/devices/${device.id}`)}
                          className="text-sm font-medium hover:underline"
                          style={{ color: "var(--text-link)" }}
                        >
                          {device.device_name || "Unnamed Device"}
                        </button>
                        <p className="text-xs font-mono" style={{ color: "var(--text-muted)" }}>
                          {device.device_id || device.id}
                        </p>
                        {device.device_location && (
                          <p className="text-xs" style={{ color: "var(--text-muted)" }}>
                            {device.device_location}
                          </p>
                        )}
                      </div>
                    </div>
                    {canEdit && (
                      <button
                        onClick={() => handleUnassignDevice(device.id)}
                        className="text-xs hover:opacity-80 cursor-pointer"
                        style={{ color: "var(--danger)" }}
                      >
                        Remove
                      </button>
                    )}
                  </div>
                ))}
              </div>
            )}
          </section>

          {/* Issues and Notes */}
          <NotesPanel userId={id} />
        </div>
      </div>

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