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";
import {
  getLocalizedValue,
  getLanguageName,
  normalizeColor,
  formatDuration,
} from "./melodyUtils";

function Field({ label, children }) {
  return (
    <div>
      <dt className="text-xs font-medium uppercase tracking-wide" style={{ color: "var(--text-muted)" }}>
        {label}
      </dt>
      <dd className="mt-1 text-sm" style={{ color: "var(--text-primary)" }}>{children || "-"}</dd>
    </div>
  );
}

export default function MelodyDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("melodies", "edit");

  const [melody, setMelody] = useState(null);
  const [files, setFiles] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showDelete, setShowDelete] = useState(false);
  const [displayLang, setDisplayLang] = useState("en");
  const [melodySettings, setMelodySettings] = useState(null);

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

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

  const loadData = async () => {
    setLoading(true);
    try {
      const [m, f] = await Promise.all([
        api.get(`/melodies/${id}`),
        api.get(`/melodies/${id}/files`),
      ]);
      setMelody(m);
      setFiles(f);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    try {
      await api.delete(`/melodies/${id}`);
      navigate("/melodies");
    } 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) {
    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 (!melody) return null;

  const info = melody.information || {};
  const settings = melody.default_settings || {};
  const languages = melodySettings?.available_languages || ["en"];
  const displayName = getLocalizedValue(info.name, displayLang, "Untitled Melody");

  const badgeStyle = (active) => ({
    backgroundColor: active ? "var(--success-bg)" : "var(--bg-card-hover)",
    color: active ? "var(--success-text)" : "var(--text-muted)",
  });

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <button
            onClick={() => navigate("/melodies")}
            className="text-sm mb-2 inline-block"
            style={{ color: "var(--accent)" }}
          >
            &larr; Back to Melodies
          </button>
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>{displayName}</h1>
            {languages.length > 1 && (
              <select
                value={displayLang}
                onChange={(e) => setDisplayLang(e.target.value)}
                className="text-xs px-2 py-1 rounded border"
              >
                {languages.map((l) => (
                  <option key={l} value={l}>
                    {getLanguageName(l)}
                  </option>
                ))}
              </select>
            )}
          </div>
        </div>
        {canEdit && (
          <div className="flex gap-2">
            <button
              onClick={() => navigate(`/melodies/${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-btn)", color: "var(--text-white)" }}
            >
              Delete
            </button>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
        {/* Left column */}
        <div className="space-y-6">
          {/* Melody Information */}
          <section
            className="rounded-lg p-6 border"
            style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
          >
            <h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>
              Melody Information
            </h2>
            <dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <Field label="Type">
                <span className="capitalize">{melody.type}</span>
              </Field>
              <Field label="Tone">
                <span className="capitalize">{info.melodyTone}</span>
              </Field>
              <Field label="Total Active Notes (bells)">{info.totalNotes}</Field>
              <Field label="Steps">{info.steps}</Field>
              <Field label="Min Speed">{info.minSpeed}</Field>
              <Field label="Max Speed">{info.maxSpeed}</Field>
              <Field label="Color">
                {info.color ? (
                  <span className="inline-flex items-center gap-2">
                    <span
                      className="w-4 h-4 rounded inline-block border"
                      style={{ backgroundColor: normalizeColor(info.color), borderColor: "var(--border-primary)" }}
                    />
                    {info.color}
                  </span>
                ) : (
                  "-"
                )}
              </Field>
              <Field label="True Ring">
                <span className="px-2 py-0.5 text-xs rounded-full" style={badgeStyle(info.isTrueRing)}>
                  {info.isTrueRing ? "Yes" : "No"}
                </span>
              </Field>
              <div className="col-span-2 md:col-span-3">
                <Field label="Description">
                  {getLocalizedValue(info.description, displayLang)}
                </Field>
              </div>
              <div className="col-span-2 md:col-span-3">
                <Field label="Custom Tags">
                  {info.customTags?.length > 0 ? (
                    <div className="flex flex-wrap gap-1 mt-1">
                      {info.customTags.map((tag) => (
                        <span
                          key={tag}
                          className="px-2 py-0.5 text-xs rounded-full"
                          style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}
                        >
                          {tag}
                        </span>
                      ))}
                    </div>
                  ) : (
                    "-"
                  )}
                </Field>
              </div>
            </dl>
          </section>

          {/* Identifiers */}
          <section
            className="rounded-lg p-6 border"
            style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
          >
            <h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>
              Identifiers
            </h2>
            <dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <Field label="Document ID">{melody.id}</Field>
              <Field label="PID (Playback ID)">{melody.pid}</Field>
              <Field label="UID">{melody.uid}</Field>
              <div className="col-span-2 md:col-span-3">
                <Field label="URL">{melody.url}</Field>
              </div>
            </dl>
          </section>
        </div>

        {/* Right column */}
        <div className="space-y-6">
          {/* Default Settings */}
          <section
            className="rounded-lg p-6 border"
            style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
          >
            <h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>
              Default Settings
            </h2>
            <dl className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <Field label="Speed">{settings.speed}%</Field>
              <Field label="Duration">{formatDuration(settings.duration)}</Field>
              <Field label="Total Run Duration">{settings.totalRunDuration}</Field>
              <Field label="Pause Duration">{settings.pauseDuration}</Field>
              <Field label="Infinite Loop">
                <span className="px-2 py-0.5 text-xs rounded-full" style={badgeStyle(settings.infiniteLoop)}>
                  {settings.infiniteLoop ? "Yes" : "No"}
                </span>
              </Field>
              <div className="col-span-2 md:col-span-3">
                <Field label="Echo Ring">
                  {settings.echoRing?.length > 0
                    ? settings.echoRing.join(", ")
                    : "-"}
                </Field>
              </div>
              <div className="col-span-2 md:col-span-3">
                <Field label="Note Assignments">
                  {settings.noteAssignments?.length > 0
                    ? settings.noteAssignments.join(", ")
                    : "-"}
                </Field>
              </div>
            </dl>
          </section>

          {/* Files */}
          <section
            className="rounded-lg p-6 border"
            style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
          >
            <h2 className="text-lg font-semibold mb-4" style={{ color: "var(--text-heading)" }}>Files</h2>
            <dl className="space-y-4">
              <Field label="Binary File">
                {files.binary_url ? (
                  <a
                    href={files.binary_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="underline"
                    style={{ color: "var(--accent)" }}
                  >
                    Download binary
                  </a>
                ) : (
                  <span style={{ color: "var(--text-muted)" }}>Not uploaded</span>
                )}
              </Field>
              <Field label="Audio Preview">
                {files.preview_url ? (
                  <div className="space-y-1">
                    <audio controls src={files.preview_url} className="h-8" />
                    <a
                      href={files.preview_url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="underline text-xs"
                      style={{ color: "var(--accent)" }}
                    >
                      Download preview
                    </a>
                  </div>
                ) : (
                  <span style={{ color: "var(--text-muted)" }}>Not uploaded</span>
                )}
              </Field>
            </dl>
          </section>
        </div>
      </div>

      <ConfirmDialog
        open={showDelete}
        title="Delete Melody"
        message={`Are you sure you want to delete "${displayName}"? This will also delete any uploaded files. This action cannot be undone.`}
        onConfirm={handleDelete}
        onCancel={() => setShowDelete(false)}
      />
    </div>
  );
}
