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

const NOTE_CATEGORIES = ["general", "maintenance", "installation", "other"];
const ISSUE_CATEGORIES = ["issue", "action_item"];
const ALL_CATEGORIES = ["general", "maintenance", "installation", "issue", "action_item", "other"];

const categoryStyle = (cat) => {
  switch (cat) {
    case "issue":
      return { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" };
    case "action_item":
      return { backgroundColor: "var(--badge-blue-bg, rgba(59,130,246,0.15))", color: "var(--badge-blue-text, #3b82f6)" };
    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)" };
  }
};

const helpdeskTypeStyle = (type) => {
  switch (type?.toLowerCase()) {
    case "problem":
      return { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" };
    case "suggestion":
      return { backgroundColor: "var(--badge-blue-bg, rgba(59,130,246,0.15))", color: "var(--badge-blue-text, #3b82f6)" };
    case "question":
      return { backgroundColor: "var(--warning-bg, rgba(245,158,11,0.15))", color: "var(--warning-text, #f59e0b)" };
    default:
      return { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" };
  }
};

const formatLabel = (s) => s ? s.replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase()) : "";

export default function NotesPanel({ deviceId, userId, initialTab }) {
  const [notes, setNotes] = useState([]);
  const [helpdeskMessages, setHelpdeskMessages] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [showForm, setShowForm] = useState(false);
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [category, setCategory] = useState("general");
  const [saving, setSaving] = useState(false);
  const [activeTab, setActiveTab] = useState(initialTab || "notes");

  useEffect(() => {
    if (initialTab) setActiveTab(initialTab);
  }, [initialTab]);
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("equipment", "edit");

  const fetchNotes = async () => {
    setLoading(true);
    setError("");
    try {
      const params = new URLSearchParams();
      if (deviceId) params.set("device_id", deviceId);
      if (userId) params.set("user_id", userId);
      const qs = params.toString();
      const data = await api.get(`/equipment/notes${qs ? `?${qs}` : ""}`);
      setNotes(data.notes);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const fetchHelpdesk = async () => {
    try {
      const params = new URLSearchParams();
      if (deviceId) params.set("device_id", deviceId);
      if (userId) params.set("user_id", userId);
      const qs = params.toString();
      const data = await api.get(`/helpdesk${qs ? `?${qs}` : ""}`);
      setHelpdeskMessages(data.messages);
    } catch {
      // Silently fail
    }
  };

  useEffect(() => {
    fetchNotes();
    fetchHelpdesk();
  }, [deviceId, userId]);

  const handleCreate = async (e) => {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      await api.post("/equipment/notes", {
        title,
        content,
        category,
        device_id: deviceId || null,
        user_id: userId || null,
      });
      setTitle("");
      setContent("");
      setCategory("general");
      setShowForm(false);
      fetchNotes();
    } catch (err) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await api.delete(`/equipment/notes/${deleteTarget.id}`);
      setDeleteTarget(null);
      fetchNotes();
    } catch (err) {
      setError(err.message);
      setDeleteTarget(null);
    }
  };

  const handleToggleStatus = async (note) => {
    try {
      const newStatus = note.status === "completed" ? "" : "completed";
      await api.patch(`/equipment/notes/${note.id}/status`, { status: newStatus });
      fetchNotes();
    } catch (err) {
      setError(err.message);
    }
  };

  const handleToggleAcknowledged = async (msg) => {
    try {
      await api.patch(`/helpdesk/${msg.id}/acknowledge`);
      fetchHelpdesk();
    } catch (err) {
      setError(err.message);
    }
  };

  // Split notes
  const noteItems = notes.filter(n => NOTE_CATEGORIES.includes(n.category));
  const issueItems = notes.filter(n => ISSUE_CATEGORIES.includes(n.category));

  const tabs = [
    { key: "notes", label: "Notes", count: noteItems.length },
    { key: "issues", label: "Issues", count: issueItems.length },
    { key: "messages", label: "Messages", count: helpdeskMessages.length },
  ];

  const totalCount = notes.length + helpdeskMessages.length;

  const inputClass = "w-full px-3 py-2 rounded-md text-sm border";

  const renderNoteItem = (note, showStatus = false) => (
    <div
      key={note.id}
      className="p-3 rounded-md border cursor-pointer hover:opacity-90 transition-colors"
      style={{
        backgroundColor: "var(--bg-primary)",
        borderColor: "var(--border-primary)",
        opacity: note.status === "completed" ? 0.6 : 1,
      }}
      onClick={() => navigate(`/equipment/notes/${note.id}`)}
    >
      <div className="flex items-start justify-between gap-2">
        <div className="flex items-start gap-2 flex-1 min-w-0">
          {showStatus && (
            <button
              onClick={(e) => { e.stopPropagation(); handleToggleStatus(note); }}
              className="w-5 h-5 rounded border-2 flex items-center justify-center cursor-pointer transition-colors shrink-0 mt-0.5"
              style={{
                borderColor: note.status === "completed" ? "var(--success-text)" : "var(--border-primary)",
                backgroundColor: note.status === "completed" ? "var(--success-bg)" : "transparent",
                color: "var(--success-text)",
                fontSize: "0.7rem",
              }}
              title={note.status === "completed" ? "Mark as open" : "Mark as completed"}
            >
              {note.status === "completed" && "✓"}
            </button>
          )}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-1">
              <span className="px-2 py-0.5 text-xs rounded-full shrink-0" style={categoryStyle(note.category)}>
                {formatLabel(note.category)}
              </span>
              <span
                className="text-sm font-medium truncate"
                style={{
                  color: "var(--text-heading)",
                  textDecoration: note.status === "completed" ? "line-through" : "none",
                }}
              >
                {note.title}
              </span>
            </div>
            <p className="text-xs" style={{ color: "var(--text-muted)", display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden", whiteSpace: "pre-wrap" }}>{note.content}</p>
            <p className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
              {note.created_by && `${note.created_by} · `}{note.created_at}
            </p>
          </div>
        </div>
        {canEdit && (
          <button
            onClick={(e) => { e.stopPropagation(); setDeleteTarget(note); }}
            className="text-xs hover:opacity-80 shrink-0 cursor-pointer"
            style={{ color: "var(--danger)" }}
          >
            Delete
          </button>
        )}
      </div>
    </div>
  );

  const renderHelpdeskItem = (msg) => (
    <div
      key={msg.id}
      className="p-3 rounded-md border transition-colors"
      style={{
        backgroundColor: "var(--bg-primary)",
        borderColor: "var(--border-primary)",
        opacity: msg.acknowledged ? 0.6 : 1,
      }}
    >
      <div className="flex items-start justify-between gap-2">
        <div className="flex items-start gap-2 flex-1 min-w-0">
          {canEdit && (
            <button
              onClick={() => handleToggleAcknowledged(msg)}
              className="w-5 h-5 rounded border-2 flex items-center justify-center cursor-pointer transition-colors shrink-0 mt-0.5"
              style={{
                borderColor: msg.acknowledged ? "var(--success-text)" : "var(--border-primary)",
                backgroundColor: msg.acknowledged ? "var(--success-bg)" : "transparent",
                color: "var(--success-text)",
                fontSize: "0.7rem",
              }}
              title={msg.acknowledged ? `Acknowledged by ${msg.acknowledged_by}` : "Mark as acknowledged"}
            >
              {msg.acknowledged && "✓"}
            </button>
          )}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-1">
              <span className="px-2 py-0.5 text-xs rounded-full shrink-0" style={helpdeskTypeStyle(msg.type)}>
                {msg.type || "Other"}
              </span>
              <span className="text-sm font-medium truncate" style={{ color: "var(--text-heading)" }}>
                {msg.subject || "No subject"}
              </span>
            </div>
            <p className="text-xs" style={{ color: "var(--text-muted)", display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden", whiteSpace: "pre-wrap" }}>{msg.message}</p>
            <p className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
              {msg.sender_name && `${msg.sender_name} · `}{msg.phone && `${msg.phone} · `}{msg.date_sent}
            </p>
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <section
      className="rounded-lg border p-6"
      style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", minWidth: 0, overflow: "hidden" }}
    >
      <div className="flex items-center justify-between mb-3">
        <h2 className="text-lg font-semibold" style={{ color: "var(--text-heading)" }}>
          Issues & Notes ({totalCount})
        </h2>
        <div className="flex gap-2">
          {canEdit && activeTab !== "messages" && (
            <button
              onClick={() => setShowForm(!showForm)}
              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)" }}
            >
              {showForm ? "Cancel" : "Add Note"}
            </button>
          )}
          <button
            onClick={() => {
              const params = new URLSearchParams();
              if (deviceId) params.set("device_id", deviceId);
              if (userId) params.set("user_id", userId);
              navigate(`/equipment/notes?${params}`);
            }}
            className="px-3 py-1.5 text-xs rounded-md hover:opacity-80 transition-colors cursor-pointer"
            style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-primary)" }}
          >
            View All
          </button>
        </div>
      </div>

      {/* Compact tabs */}
      <div className="flex gap-1 mb-4 border-b" style={{ borderColor: "var(--border-primary)" }}>
        {tabs.map((tab) => (
          <button
            key={tab.key}
            onClick={() => setActiveTab(tab.key)}
            className="px-3 py-2 text-xs font-medium transition-colors cursor-pointer"
            style={{
              color: activeTab === tab.key ? "var(--accent)" : "var(--text-muted)",
              borderBottom: activeTab === tab.key ? "2px solid var(--accent)" : "2px solid transparent",
              marginBottom: "-1px",
            }}
          >
            {tab.label} ({tab.count})
          </button>
        ))}
      </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>
      )}

      {showForm && activeTab !== "messages" && (
        <form onSubmit={handleCreate} className="mb-4 p-4 rounded-md border" style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-primary)" }}>
          <div className="space-y-3">
            <div className="flex gap-3">
              <div className="flex-1">
                <input
                  type="text"
                  required
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  placeholder="Note title"
                  className={inputClass}
                  style={{ backgroundColor: "var(--bg-card)", color: "var(--text-primary)", borderColor: "var(--border-primary)" }}
                />
              </div>
              <select
                value={category}
                onChange={(e) => setCategory(e.target.value)}
                className="px-3 py-2 rounded-md text-sm border"
                style={{ backgroundColor: "var(--bg-card)", color: "var(--text-primary)", borderColor: "var(--border-primary)" }}
              >
                {ALL_CATEGORIES.map((c) => (
                  <option key={c} value={c}>{formatLabel(c)}</option>
                ))}
              </select>
            </div>
            <textarea
              required
              value={content}
              onChange={(e) => setContent(e.target.value)}
              rows={3}
              placeholder="Note content..."
              className={inputClass}
              style={{ backgroundColor: "var(--bg-card)", color: "var(--text-primary)", borderColor: "var(--border-primary)", resize: "vertical" }}
            />
            <div className="flex justify-end">
              <button
                type="submit"
                disabled={saving}
                className="px-4 py-2 text-sm rounded-md hover:opacity-90 disabled:opacity-50 transition-colors"
                style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
              >
                {saving ? "Saving..." : "Save Note"}
              </button>
            </div>
          </div>
        </form>
      )}

      {loading ? (
        <p className="text-sm py-4 text-center" style={{ color: "var(--text-muted)" }}>Loading...</p>
      ) : (
        <>
          {activeTab === "notes" && (
            noteItems.length === 0 ? (
              <p className="text-sm" style={{ color: "var(--text-muted)" }}>No notes yet.</p>
            ) : (
              <div className="space-y-2">{noteItems.map(n => renderNoteItem(n, false))}</div>
            )
          )}
          {activeTab === "issues" && (
            issueItems.length === 0 ? (
              <p className="text-sm" style={{ color: "var(--text-muted)" }}>No issues or action items.</p>
            ) : (
              <div className="space-y-2">{issueItems.map(n => renderNoteItem(n, true))}</div>
            )
          )}
          {activeTab === "messages" && (
            helpdeskMessages.length === 0 ? (
              <p className="text-sm" style={{ color: "var(--text-muted)" }}>No client messages.</p>
            ) : (
              <div className="space-y-2">{helpdeskMessages.map(renderHelpdeskItem)}</div>
            )
          )}
        </>
      )}

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