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

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

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 NoteList() {
  const [notes, setNotes] = useState([]);
  const [helpdeskMessages, setHelpdeskMessages] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [search, setSearch] = useState("");
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [hoveredRow, setHoveredRow] = useState(null);
  const [activeTab, setActiveTab] = useState("notes");
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("equipment", "edit");
  const [searchParams] = useSearchParams();

  const deviceIdFilter = searchParams.get("device_id") || "";
  const userIdFilter = searchParams.get("user_id") || "";

  const fetchNotes = async () => {
    setLoading(true);
    setError("");
    try {
      const params = new URLSearchParams();
      if (search) params.set("search", search);
      if (deviceIdFilter) params.set("device_id", deviceIdFilter);
      if (userIdFilter) params.set("user_id", userIdFilter);
      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 (deviceIdFilter) params.set("device_id", deviceIdFilter);
      if (userIdFilter) params.set("user_id", userIdFilter);
      const qs = params.toString();
      const data = await api.get(`/helpdesk${qs ? `?${qs}` : ""}`);
      setHelpdeskMessages(data.messages);
    } catch {
      // Silently fail for helpdesk if not available
    }
  };

  useEffect(() => {
    fetchNotes();
    fetchHelpdesk();
  }, [search, deviceIdFilter, userIdFilter]);

  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 by tab
  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 & Action Items", count: issueItems.length },
    { key: "messages", label: "Client Messages", count: helpdeskMessages.length },
  ];

  const renderNotesTable = (items, showStatus = false) => {
    if (items.length === 0) {
      return (
        <div
          className="rounded-lg p-8 text-center text-sm border"
          style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}
        >
          No items found.
        </div>
      );
    }

    return (
      <div
        className="rounded-lg overflow-hidden border"
        style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
      >
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
                {showStatus && (
                  <th className="px-4 py-3 text-left font-medium w-12" style={{ color: "var(--text-secondary)" }} />
                )}
                <th className="px-4 py-3 text-left font-medium w-28" style={{ color: "var(--text-secondary)" }}>Category</th>
                <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Title</th>
                <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Device</th>
                <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>User</th>
                <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Created</th>
                {canEdit && (
                  <th className="px-4 py-3 text-left font-medium w-24" style={{ color: "var(--text-secondary)" }} />
                )}
              </tr>
            </thead>
            <tbody>
              {items.map((note, index) => (
                <tr
                  key={note.id}
                  onClick={() => navigate(`/equipment/notes/${note.id}`)}
                  className="cursor-pointer"
                  style={{
                    borderBottom: index < items.length - 1 ? "1px solid var(--border-primary)" : "none",
                    backgroundColor: hoveredRow === note.id ? "var(--bg-card-hover)" : index % 2 === 1 ? "var(--bg-row-alt)" : "transparent",
                    opacity: note.status === "completed" ? 0.6 : 1,
                  }}
                  onMouseEnter={() => setHoveredRow(note.id)}
                  onMouseLeave={() => setHoveredRow(null)}
                >
                  {showStatus && (
                    <td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
                      {canEdit ? (
                        <button
                          onClick={() => handleToggleStatus(note)}
                          className="w-5 h-5 rounded border-2 flex items-center justify-center cursor-pointer transition-colors"
                          style={{
                            borderColor: note.status === "completed" ? "var(--success-text)" : "var(--border-primary)",
                            backgroundColor: note.status === "completed" ? "var(--success-bg)" : "transparent",
                            color: "var(--success-text)",
                          }}
                          title={note.status === "completed" ? "Mark as open" : "Mark as completed"}
                        >
                          {note.status === "completed" && "✓"}
                        </button>
                      ) : (
                        <span
                          className="w-5 h-5 rounded border-2 flex items-center justify-center"
                          style={{
                            borderColor: note.status === "completed" ? "var(--success-text)" : "var(--border-primary)",
                            backgroundColor: note.status === "completed" ? "var(--success-bg)" : "transparent",
                            color: "var(--success-text)",
                          }}
                        >
                          {note.status === "completed" && "✓"}
                        </span>
                      )}
                    </td>
                  )}
                  <td className="px-4 py-3">
                    <span className="px-2 py-0.5 text-xs rounded-full" style={categoryStyle(note.category)}>
                      {formatLabel(note.category) || "General"}
                    </span>
                  </td>
                  <td className="px-4 py-3 font-medium" style={{
                    color: "var(--text-heading)",
                    textDecoration: note.status === "completed" ? "line-through" : "none",
                  }}>
                    {note.title || "Untitled"}
                  </td>
                  <td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>{note.device_name || "-"}</td>
                  <td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>{note.user_name || "-"}</td>
                  <td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>{note.created_at || "-"}</td>
                  {canEdit && (
                    <td className="px-4 py-3">
                      <div className="flex gap-2" onClick={(e) => e.stopPropagation()}>
                        <button onClick={() => navigate(`/equipment/notes/${note.id}/edit`)} className="hover:opacity-80 text-xs cursor-pointer" style={{ color: "var(--text-link)" }}>Edit</button>
                        <button onClick={() => setDeleteTarget(note)} className="hover:opacity-80 text-xs cursor-pointer" style={{ color: "var(--danger)" }}>Delete</button>
                      </div>
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  };

  const renderHelpdeskMessages = () => {
    const filtered = search
      ? helpdeskMessages.filter(m =>
          (m.subject || "").toLowerCase().includes(search.toLowerCase()) ||
          (m.message || "").toLowerCase().includes(search.toLowerCase())
        )
      : helpdeskMessages;

    if (filtered.length === 0) {
      return (
        <div
          className="rounded-lg p-8 text-center text-sm border"
          style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}
        >
          No client messages found.
        </div>
      );
    }

    return (
      <div
        className="rounded-lg overflow-hidden border"
        style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
      >
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
                <th className="px-4 py-3 text-left font-medium w-12" style={{ color: "var(--text-secondary)" }} />
                <th className="px-4 py-3 text-left font-medium w-28" style={{ color: "var(--text-secondary)" }}>Type</th>
                <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Subject</th>
                <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>From</th>
                <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Phone</th>
                <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Date</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((msg, index) => (
                <tr
                  key={msg.id}
                  style={{
                    borderBottom: index < filtered.length - 1 ? "1px solid var(--border-primary)" : "none",
                    backgroundColor: hoveredRow === msg.id ? "var(--bg-card-hover)" : index % 2 === 1 ? "var(--bg-row-alt)" : "transparent",
                    opacity: msg.acknowledged ? 0.6 : 1,
                  }}
                  onMouseEnter={() => setHoveredRow(msg.id)}
                  onMouseLeave={() => setHoveredRow(null)}
                >
                  <td className="px-4 py-3">
                    {canEdit && (
                      <button
                        onClick={(e) => { e.stopPropagation(); handleToggleAcknowledged(msg); }}
                        className="w-5 h-5 rounded border-2 flex items-center justify-center cursor-pointer transition-colors"
                        style={{
                          borderColor: msg.acknowledged ? "var(--success-text)" : "var(--border-primary)",
                          backgroundColor: msg.acknowledged ? "var(--success-bg)" : "transparent",
                          color: "var(--success-text)",
                        }}
                        title={msg.acknowledged ? `Acknowledged by ${msg.acknowledged_by}` : "Mark as acknowledged"}
                      >
                        {msg.acknowledged && "✓"}
                      </button>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <span className="px-2 py-0.5 text-xs rounded-full" style={helpdeskTypeStyle(msg.type)}>
                      {msg.type || "Other"}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="font-medium" style={{ color: "var(--text-heading)" }}>{msg.subject || "No subject"}</div>
                    <div className="text-xs truncate mt-0.5" style={{ color: "var(--text-muted)", maxWidth: 300 }}>{msg.message}</div>
                  </td>
                  <td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>{msg.sender_name || "-"}</td>
                  <td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>{msg.phone || "-"}</td>
                  <td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>{msg.date_sent || "-"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>BlackBox</h1>
        {canEdit && activeTab !== "messages" && (
          <button
            onClick={() => {
              const params = new URLSearchParams();
              if (deviceIdFilter) params.set("device_id", deviceIdFilter);
              if (userIdFilter) params.set("user_id", userIdFilter);
              const qs = params.toString();
              navigate(`/equipment/notes/new${qs ? `?${qs}` : ""}`);
            }}
            className="px-4 py-2 text-sm rounded-md hover:opacity-90 transition-colors cursor-pointer"
            style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
          >
            Add Note
          </button>
        )}
      </div>

      {/* 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-4 py-2.5 text-sm 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}
            <span className="ml-2 text-xs" style={{ opacity: 0.7 }}>({tab.count})</span>
          </button>
        ))}
      </div>

      <div className="mb-4">
        <SearchBar
          onSearch={setSearch}
          placeholder={activeTab === "messages" ? "Search by subject or message..." : "Search by title or content..."}
        />
      </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>
      )}

      {loading ? (
        <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
      ) : (
        <>
          {activeTab === "notes" && renderNotesTable(noteItems, false)}
          {activeTab === "issues" && renderNotesTable(issueItems, true)}
          {activeTab === "messages" && renderHelpdeskMessages()}
        </>
      )}

      <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)}
      />
    </div>
  );
}
