import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import api from "../api/client";
import { useAuth } from "../auth/AuthContext";
import SearchBar from "../components/SearchBar";
import ConfirmDialog from "../components/ConfirmDialog";
import {
  getLocalizedValue,
  getLanguageName,
  normalizeColor,
  formatDuration,
} from "./melodyUtils";

const MELODY_TYPES = ["", "orthodox", "catholic", "all"];
const MELODY_TONES = ["", "normal", "festive", "cheerful", "lamentation"];

// All available columns with their defaults
const ALL_COLUMNS = [
  { key: "status", label: "Status", defaultOn: true },
  { key: "color", label: "Color", defaultOn: true },
  { key: "name", label: "Name", defaultOn: true, alwaysOn: true },
  { key: "description", label: "Description", defaultOn: false },
  { key: "type", label: "Type", defaultOn: true },
  { key: "tone", label: "Tone", defaultOn: true },
  { key: "totalNotes", label: "Total Notes", defaultOn: true },
  { key: "minSpeed", label: "Min Speed", defaultOn: false },
  { key: "maxSpeed", label: "Max Speed", defaultOn: false },
  { key: "tags", label: "Tags", defaultOn: false },
  { key: "speed", label: "Speed", defaultOn: false },
  { key: "duration", label: "Duration", defaultOn: false },
  { key: "totalRunDuration", label: "Total Run", defaultOn: false },
  { key: "pauseDuration", label: "Pause", defaultOn: false },
  { key: "infiniteLoop", label: "Infinite", defaultOn: false },
  { key: "noteAssignments", label: "Note Assignments", defaultOn: false },
  { key: "isTrueRing", label: "True Ring", defaultOn: true },
  { key: "docId", label: "Document ID", defaultOn: false },
  { key: "pid", label: "PID", defaultOn: false },
];

function getDefaultVisibleColumns() {
  const saved = localStorage.getItem("melodyListColumns");
  if (saved) {
    try {
      return JSON.parse(saved);
    } catch {
      // ignore
    }
  }
  return ALL_COLUMNS.filter((c) => c.defaultOn).map((c) => c.key);
}

export default function MelodyList() {
  const [melodies, setMelodies] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [search, setSearch] = useState("");
  const [typeFilter, setTypeFilter] = useState("");
  const [toneFilter, setToneFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [displayLang, setDisplayLang] = useState("en");
  const [melodySettings, setMelodySettings] = useState(null);
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [unpublishTarget, setUnpublishTarget] = useState(null);
  const [actionLoading, setActionLoading] = useState(null);
  const [visibleColumns, setVisibleColumns] = useState(getDefaultVisibleColumns);
  const [showColumnPicker, setShowColumnPicker] = useState(false);
  const columnPickerRef = useRef(null);
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("melodies", "edit");

  useEffect(() => {
    api.get("/settings/melody").then((ms) => {
      setMelodySettings(ms);
      setDisplayLang(ms.primary_language || "en");
    });
  }, []);

  // Close column picker on outside click
  useEffect(() => {
    const handleClick = (e) => {
      if (columnPickerRef.current && !columnPickerRef.current.contains(e.target)) {
        setShowColumnPicker(false);
      }
    };
    if (showColumnPicker) {
      document.addEventListener("mousedown", handleClick);
      return () => document.removeEventListener("mousedown", handleClick);
    }
  }, [showColumnPicker]);

  const fetchMelodies = async () => {
    setLoading(true);
    setError("");
    try {
      const params = new URLSearchParams();
      if (search) params.set("search", search);
      if (typeFilter) params.set("type", typeFilter);
      if (toneFilter) params.set("tone", toneFilter);
      if (statusFilter) params.set("status", statusFilter);
      const qs = params.toString();
      const data = await api.get(`/melodies${qs ? `?${qs}` : ""}`);
      setMelodies(data.melodies);
      setTotal(data.total);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMelodies();
  }, [search, typeFilter, toneFilter, statusFilter]);

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

  const handlePublish = async (row) => {
    setActionLoading(row.id);
    try {
      await api.post(`/melodies/${row.id}/publish`);
      fetchMelodies();
    } catch (err) {
      setError(err.message);
    } finally {
      setActionLoading(null);
    }
  };

  const handleUnpublish = async () => {
    if (!unpublishTarget) return;
    setActionLoading(unpublishTarget.id);
    try {
      await api.post(`/melodies/${unpublishTarget.id}/unpublish`);
      setUnpublishTarget(null);
      fetchMelodies();
    } catch (err) {
      setError(err.message);
      setUnpublishTarget(null);
    } finally {
      setActionLoading(null);
    }
  };

  const toggleColumn = (key) => {
    const col = ALL_COLUMNS.find((c) => c.key === key);
    if (col?.alwaysOn) return;
    setVisibleColumns((prev) => {
      const next = prev.includes(key)
        ? prev.filter((k) => k !== key)
        : [...prev, key];
      localStorage.setItem("melodyListColumns", JSON.stringify(next));
      return next;
    });
  };

  const isVisible = (key) => visibleColumns.includes(key);

  const getDisplayName = (nameVal) =>
    getLocalizedValue(nameVal, displayLang, "Untitled");

  const renderCellValue = (key, row) => {
    const info = row.information || {};
    const ds = row.default_settings || {};
    switch (key) {
      case "status":
        return (
          <span
            className="px-2 py-0.5 text-xs font-semibold rounded-full"
            style={row.status === "published"
              ? { backgroundColor: "rgba(22,163,74,0.15)", color: "#22c55e" }
              : { backgroundColor: "rgba(156,163,175,0.15)", color: "#9ca3af" }
            }
          >
            {row.status === "published" ? "Live" : "Draft"}
          </span>
        );
      case "color":
        return info.color ? (
          <span
            className="inline-block w-3 h-8 rounded-sm"
            style={{ backgroundColor: normalizeColor(info.color) }}
            title={info.color}
          />
        ) : (
          <span className="inline-block w-3 h-8 rounded-sm" style={{ backgroundColor: "var(--border-primary)" }} />
        );
      case "name":
        return (
          <div>
            <span className="font-medium" style={{ color: "var(--text-heading)" }}>
              {getDisplayName(info.name)}
            </span>
            {isVisible("description") && (
              <p className="text-xs mt-0.5 truncate max-w-xs" style={{ color: "var(--text-muted)" }}>
                {getLocalizedValue(info.description, displayLang) || "-"}
              </p>
            )}
          </div>
        );
      case "type":
        return <span className="capitalize">{row.type}</span>;
      case "tone":
        return <span className="capitalize">{info.melodyTone || "-"}</span>;
      case "totalNotes":
        return info.totalNotes ?? "-";
      case "minSpeed":
        return info.minSpeed ?? "-";
      case "maxSpeed":
        return info.maxSpeed ?? "-";
      case "tags":
        return info.customTags?.length > 0 ? (
          <div className="flex flex-wrap gap-1">
            {info.customTags.map((tag) => (
              <span
                key={tag}
                className="px-1.5 py-0.5 text-xs rounded-full"
                style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
              >
                {tag}
              </span>
            ))}
          </div>
        ) : (
          "-"
        );
      case "speed":
        return ds.speed != null ? `${ds.speed}%` : "-";
      case "duration":
        return ds.duration != null ? formatDuration(ds.duration) : "-";
      case "totalRunDuration":
        return ds.totalRunDuration ?? "-";
      case "pauseDuration":
        return ds.pauseDuration ?? "-";
      case "infiniteLoop":
        return (
          <span
            className="px-2 py-0.5 text-xs rounded-full"
            style={{
              backgroundColor: ds.infiniteLoop ? "var(--success-bg)" : "var(--bg-card-hover)",
              color: ds.infiniteLoop ? "var(--success-text)" : "var(--text-muted)",
            }}
          >
            {ds.infiniteLoop ? "Yes" : "No"}
          </span>
        );
      case "noteAssignments":
        return ds.noteAssignments?.length > 0
          ? ds.noteAssignments.join(", ")
          : "-";
      case "isTrueRing":
        return (
          <span
            className="px-2 py-0.5 text-xs rounded-full"
            style={{
              backgroundColor: info.isTrueRing ? "var(--success-bg)" : "var(--bg-card-hover)",
              color: info.isTrueRing ? "var(--success-text)" : "var(--text-muted)",
            }}
          >
            {info.isTrueRing ? "Yes" : "No"}
          </span>
        );
      case "docId":
        return (
          <span className="font-mono text-xs" style={{ color: "var(--text-muted)" }}>{row.id}</span>
        );
      case "pid":
        return row.pid || "-";
      default:
        return "-";
    }
  };

  // Build visible column list (description is rendered inside name, not as its own column)
  const activeColumns = ALL_COLUMNS.filter(
    (c) => c.key !== "description" && isVisible(c.key)
  );

  const languages = melodySettings?.available_languages || ["en"];

  const selectClass =
    "px-3 py-2 rounded-md text-sm cursor-pointer border";

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>Melodies</h1>
        {canEdit && (
          <button
            onClick={() => navigate("/melodies/new")}
            className="px-4 py-2 text-sm rounded-md transition-colors cursor-pointer"
              style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
          >
            Add Melody
          </button>
        )}
      </div>

      <div className="mb-4 space-y-3">
        <SearchBar
          onSearch={setSearch}
          placeholder="Search by name, description, or tags..."
        />
        <div className="flex flex-wrap gap-3 items-center">
          <select
            value={typeFilter}
            onChange={(e) => setTypeFilter(e.target.value)}
            className={selectClass}
          >
            <option value="">All Types</option>
            {MELODY_TYPES.filter(Boolean).map((t) => (
              <option key={t} value={t}>
                {t.charAt(0).toUpperCase() + t.slice(1)}
              </option>
            ))}
          </select>
          <select
            value={toneFilter}
            onChange={(e) => setToneFilter(e.target.value)}
            className={selectClass}
          >
            <option value="">All Tones</option>
            {MELODY_TONES.filter(Boolean).map((t) => (
              <option key={t} value={t}>
                {t.charAt(0).toUpperCase() + t.slice(1)}
              </option>
            ))}
          </select>
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className={selectClass}
          >
            <option value="">All Statuses</option>
            <option value="published">Published (Live)</option>
            <option value="draft">Drafts</option>
          </select>
          {languages.length > 1 && (
            <select
              value={displayLang}
              onChange={(e) => setDisplayLang(e.target.value)}
              className={selectClass}
            >
              {languages.map((l) => (
                <option key={l} value={l}>
                  {getLanguageName(l)}
                </option>
              ))}
            </select>
          )}

          {/* Column visibility dropdown */}
          <div className="relative" ref={columnPickerRef}>
            <button
              type="button"
              onClick={() => setShowColumnPicker((prev) => !prev)}
              className="px-3 py-2 rounded-md text-sm transition-colors cursor-pointer flex items-center gap-1.5 border"
              style={{
                borderColor: "var(--border-primary)",
                color: "var(--text-secondary)",
              }}
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7m0 10a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 00-2 2" />
              </svg>
              Columns
            </button>
            {showColumnPicker && (
              <div
                className="absolute right-0 top-full mt-1 z-20 rounded-lg shadow-lg py-2 w-52 border"
                style={{
                  backgroundColor: "var(--bg-card)",
                  borderColor: "var(--border-primary)",
                }}
              >
                {ALL_COLUMNS.map((col) => (
                  <label
                    key={col.key}
                    className="flex items-center gap-2 px-3 py-1.5 text-sm cursor-pointer"
                    style={{
                      color: col.alwaysOn ? "var(--text-muted)" : "var(--text-primary)",
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={isVisible(col.key)}
                      onChange={() => toggleColumn(col.key)}
                      disabled={col.alwaysOn}
                      className="h-3.5 w-3.5 rounded cursor-pointer"
                    />
                    {col.label}
                  </label>
                ))}
              </div>
            )}
          </div>

          <span className="flex items-center text-sm" style={{ color: "var(--text-muted)" }}>
            {total} {total === 1 ? "melody" : "melodies"}
          </span>
        </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>
      )}

      {loading ? (
        <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
      ) : melodies.length === 0 ? (
        <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 melodies found.
        </div>
      ) : (
        <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)" }}>
                  {activeColumns.map((col) => (
                    <th
                      key={col.key}
                      className={`px-4 py-3 text-left font-medium ${
                        col.key === "color" ? "w-8 px-2" : ""
                      }`}
                      style={{ color: "var(--text-muted)" }}
                    >
                      {col.key === "color" ? "" : col.label}
                    </th>
                  ))}
                  {canEdit && (
                    <th className="px-4 py-3 text-left font-medium w-24" style={{ color: "var(--text-muted)" }} />
                  )}
                </tr>
              </thead>
              <tbody>
                {melodies.map((row) => (
                  <tr
                    key={row.id}
                    onClick={() => navigate(`/melodies/${row.id}`)}
                    className="cursor-pointer transition-colors"
                    style={{ borderBottom: "1px solid var(--border-secondary)" }}
                    onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = "var(--bg-card-hover)")}
                    onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = "transparent")}
                  >
                    {activeColumns.map((col) => (
                      <td
                        key={col.key}
                        className={`px-4 py-3 ${
                          col.key === "color" ? "w-8 px-2" : ""
                        }`}
                        style={{ color: "var(--text-primary)" }}
                      >
                        {renderCellValue(col.key, row)}
                      </td>
                    ))}
                    {canEdit && (
                      <td className="px-4 py-3">
                        <div
                          className="flex gap-2"
                          onClick={(e) => e.stopPropagation()}
                        >
                          {row.status === "draft" ? (
                            <button
                              onClick={() => handlePublish(row)}
                              disabled={actionLoading === row.id}
                              className="text-xs cursor-pointer disabled:opacity-50"
                              style={{ color: "#22c55e" }}
                            >
                              {actionLoading === row.id ? "..." : "Publish"}
                            </button>
                          ) : (
                            <button
                              onClick={() => setUnpublishTarget(row)}
                              disabled={actionLoading === row.id}
                              className="text-xs cursor-pointer disabled:opacity-50"
                              style={{ color: "#ea580c" }}
                            >
                              Unpublish
                            </button>
                          )}
                          <button
                            onClick={() => navigate(`/melodies/${row.id}/edit`)}
                            className="text-xs cursor-pointer"
                            style={{ color: "var(--text-link)" }}
                          >
                            Edit
                          </button>
                          <button
                            onClick={() => setDeleteTarget(row)}
                            className="text-xs cursor-pointer"
                            style={{ color: "var(--danger)" }}
                          >
                            Delete
                          </button>
                        </div>
                      </td>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      <ConfirmDialog
        open={!!deleteTarget}
        title="Delete Melody"
        message={`Are you sure you want to delete "${getDisplayName(deleteTarget?.information?.name)}"? This will also delete any uploaded files.`}
        onConfirm={handleDelete}
        onCancel={() => setDeleteTarget(null)}
      />

      <ConfirmDialog
        open={!!unpublishTarget}
        title="Unpublish Melody"
        message={`This melody may be in use by devices. Unpublishing will remove "${getDisplayName(unpublishTarget?.information?.name)}" from Firestore and devices will no longer have access. The melody will be kept as a draft. Continue?`}
        onConfirm={handleUnpublish}
        onCancel={() => setUnpublishTarget(null)}
      />
    </div>
  );
}
