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: "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 [displayLang, setDisplayLang] = useState("en");
  const [melodySettings, setMelodySettings] = useState(null);
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [visibleColumns, setVisibleColumns] = useState(getDefaultVisibleColumns);
  const [showColumnPicker, setShowColumnPicker] = useState(false);
  const columnPickerRef = useRef(null);
  const navigate = useNavigate();
  const { hasRole } = useAuth();
  const canEdit = hasRole("superadmin", "melody_editor");

  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);
      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]);

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await api.delete(`/melodies/${deleteTarget.id}`);
      setDeleteTarget(null);
      fetchMelodies();
    } catch (err) {
      setError(err.message);
      setDeleteTarget(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 "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 bg-gray-200" />
        );
      case "name":
        return (
          <div>
            <span className="font-medium text-gray-900">
              {getDisplayName(info.name)}
            </span>
            {isVisible("description") && (
              <p className="text-xs text-gray-500 mt-0.5 truncate max-w-xs">
                {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 bg-blue-50 text-blue-700 text-xs rounded-full"
              >
                {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 ${
              ds.infiniteLoop
                ? "bg-green-100 text-green-700"
                : "bg-gray-100 text-gray-500"
            }`}
          >
            {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 ${
              info.isTrueRing
                ? "bg-green-100 text-green-700"
                : "bg-gray-100 text-gray-500"
            }`}
          >
            {info.isTrueRing ? "Yes" : "No"}
          </span>
        );
      case "docId":
        return (
          <span className="font-mono text-xs text-gray-500">{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"];

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Melodies</h1>
        {canEdit && (
          <button
            onClick={() => navigate("/melodies/new")}
            className="px-4 py-2 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 transition-colors cursor-pointer"
          >
            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="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 cursor-pointer"
          >
            <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="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 cursor-pointer"
          >
            <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>
          {languages.length > 1 && (
            <select
              value={displayLang}
              onChange={(e) => setDisplayLang(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 cursor-pointer"
            >
              {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 border border-gray-300 rounded-md text-sm text-gray-600 hover:bg-gray-50 transition-colors cursor-pointer flex items-center gap-1.5"
            >
              <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 bg-white border border-gray-200 rounded-lg shadow-lg py-2 w-52">
                {ALL_COLUMNS.map((col) => (
                  <label
                    key={col.key}
                    className={`flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-gray-50 cursor-pointer ${
                      col.alwaysOn ? "text-gray-400" : "text-gray-700"
                    }`}
                  >
                    <input
                      type="checkbox"
                      checked={isVisible(col.key)}
                      onChange={() => toggleColumn(col.key)}
                      disabled={col.alwaysOn}
                      className="h-3.5 w-3.5 rounded border-gray-300 text-blue-600 cursor-pointer"
                    />
                    {col.label}
                  </label>
                ))}
              </div>
            )}
          </div>

          <span className="flex items-center text-sm text-gray-500">
            {total} {total === 1 ? "melody" : "melodies"}
          </span>
        </div>
      </div>

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-md p-3 mb-4">
          {error}
        </div>
      )}

      {loading ? (
        <div className="text-center py-8 text-gray-500">Loading...</div>
      ) : melodies.length === 0 ? (
        <div className="bg-white rounded-lg border border-gray-200 p-8 text-center text-gray-500 text-sm">
          No melodies found.
        </div>
      ) : (
        <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-200">
                  {activeColumns.map((col) => (
                    <th
                      key={col.key}
                      className={`px-4 py-3 text-left font-medium text-gray-600 ${
                        col.key === "color" ? "w-8 px-2" : ""
                      }`}
                    >
                      {col.key === "color" ? "" : col.label}
                    </th>
                  ))}
                  {canEdit && (
                    <th className="px-4 py-3 text-left font-medium text-gray-600 w-24" />
                  )}
                </tr>
              </thead>
              <tbody>
                {melodies.map((row) => (
                  <tr
                    key={row.id}
                    onClick={() => navigate(`/melodies/${row.id}`)}
                    className="border-b border-gray-100 last:border-0 cursor-pointer hover:bg-gray-50"
                  >
                    {activeColumns.map((col) => (
                      <td
                        key={col.key}
                        className={`px-4 py-3 text-gray-700 ${
                          col.key === "color" ? "w-8 px-2" : ""
                        }`}
                      >
                        {renderCellValue(col.key, row)}
                      </td>
                    ))}
                    {canEdit && (
                      <td className="px-4 py-3">
                        <div
                          className="flex gap-2"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <button
                            onClick={() => navigate(`/melodies/${row.id}/edit`)}
                            className="text-blue-600 hover:text-blue-800 text-xs cursor-pointer"
                          >
                            Edit
                          </button>
                          <button
                            onClick={() => setDeleteTarget(row)}
                            className="text-red-600 hover:text-red-800 text-xs cursor-pointer"
                          >
                            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)}
      />
    </div>
  );
}
