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 categoryStyle = (cat) => {
  switch (cat) {
    case "issue":
      return { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" };
    case "maintenance":
      return { backgroundColor: "var(--warning-bg, rgba(245,158,11,0.15))", color: "var(--warning-text, #f59e0b)" };
    case "installation":
      return { backgroundColor: "var(--success-bg)", color: "var(--success-text)" };
    default:
      return { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" };
  }
};

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 NoteDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("equipment", "edit");

  const [note, setNote] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showDelete, setShowDelete] = useState(false);

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

  const loadNote = async () => {
    setLoading(true);
    try {
      const data = await api.get(`/equipment/notes/${id}`);
      setNote(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

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

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

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

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <button
            onClick={() => navigate("/equipment/notes")}
            className="text-sm hover:underline mb-2 inline-block"
            style={{ color: "var(--accent)" }}
          >
            &larr; Back to Notes
          </button>
          <div className="flex items-center gap-3">
            <h1
              className="text-2xl font-bold"
              style={{ color: "var(--text-heading)" }}
            >
              {note.title || "Untitled Note"}
            </h1>
            <span
              className="px-2 py-0.5 text-xs rounded-full"
              style={categoryStyle(note.category)}
            >
              {note.category || "general"}
            </span>
          </div>
        </div>
        {canEdit && (
          <div className="flex gap-2">
            <button
              onClick={() => navigate(`/equipment/notes/${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">
          {/* Note Content */}
          <section className="ui-section-card">
            <div className="ui-section-card__title-row">
              <h2 className="ui-section-card__header-title">Content</h2>
            </div>
            <div
              className="text-sm whitespace-pre-wrap"
              style={{ color: "var(--text-primary)" }}
            >
              {note.content || "No content."}
            </div>
          </section>

          {/* Timestamps */}
          <section className="ui-section-card">
            <div className="ui-section-card__title-row">
              <h2 className="ui-section-card__header-title">Details</h2>
            </div>
            <dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <Field label="Category">
                <span
                  className="px-2 py-0.5 text-xs rounded-full"
                  style={categoryStyle(note.category)}
                >
                  {note.category || "general"}
                </span>
              </Field>
              <Field label="Created By">{note.created_by}</Field>
              <Field label="Document ID">
                <span className="font-mono text-xs" style={{ color: "var(--text-muted)" }}>
                  {note.id}
                </span>
              </Field>
              <Field label="Created At">{note.created_at}</Field>
              <Field label="Updated At">{note.updated_at}</Field>
            </dl>
          </section>
        </div>

        {/* Right Column */}
        <div className="space-y-6">
          {/* Linked Device */}
          <section className="ui-section-card">
            <div className="ui-section-card__title-row">
              <h2 className="ui-section-card__header-title">Linked Device</h2>
            </div>
            {note.device_id ? (
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium" style={{ color: "var(--text-heading)" }}>
                    {note.device_name || "Unnamed Device"}
                  </p>
                  <p className="text-xs font-mono" style={{ color: "var(--text-muted)" }}>
                    {note.device_id}
                  </p>
                </div>
                <button
                  onClick={() => navigate(`/devices/${note.device_id}`)}
                  className="text-xs hover:underline"
                  style={{ color: "var(--text-link)" }}
                >
                  View Device
                </button>
              </div>
            ) : (
              <p className="text-sm" style={{ color: "var(--text-muted)" }}>
                No device linked.
              </p>
            )}
          </section>

          {/* Linked User */}
          <section className="ui-section-card">
            <div className="ui-section-card__title-row">
              <h2 className="ui-section-card__header-title">Linked User</h2>
            </div>
            {note.user_id ? (
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium" style={{ color: "var(--text-heading)" }}>
                    {note.user_name || "Unnamed User"}
                  </p>
                  <p className="text-xs font-mono" style={{ color: "var(--text-muted)" }}>
                    {note.user_id}
                  </p>
                </div>
                <button
                  onClick={() => navigate(`/users/${note.user_id}`)}
                  className="text-xs hover:underline"
                  style={{ color: "var(--text-link)" }}
                >
                  View User
                </button>
              </div>
            ) : (
              <p className="text-sm" style={{ color: "var(--text-muted)" }}>
                No user linked.
              </p>
            )}
          </section>
        </div>
      </div>

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