import { useState, useRef } from "react";
import { useParams } from "react-router-dom";
import {
  useFeatureList,
  useCreateFeature,
  useUpdateFeature,
  useDeleteFeature,
} from "../hooks/useFeatures";
import { useExternalChangeSound } from "../hooks/useExternalChangeSound";
import type { Feature } from "../types";
import StatusBadge from "./StatusBadge";
import Modal from "./Modal";
import { playSound } from "../usePeonSounds";

const STATUSES = ["planned", "in_progress", "done", "cancelled"] as const;

export default function FeaturesPage() {
  const { id: projectId } = useParams<{ id: string }>();
  const [filterStatus, setFilterStatus] = useState("");
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState<Feature | null>(null);
  const [form, setForm] = useState({
    name: "",
    description: "",
    status: "planned",
  });

  const mutationGuard = useRef(false);
  const { data: features = [] } = useFeatureList(projectId, filterStatus || undefined);
  const createFeature = useCreateFeature(projectId!);
  const updateFeature = useUpdateFeature(projectId!);
  const deleteFeature = useDeleteFeature(projectId!);

  useExternalChangeSound(features, "i-ll-try", mutationGuard);

  const openCreate = () => {
    setEditing(null);
    setForm({ name: "", description: "", status: "planned" });
    setShowModal(true);
    playSound("what-do-you-want");
  };

  const openEdit = (f: Feature) => {
    setEditing(f);
    setForm({ name: f.name, description: f.description, status: f.status });
    setShowModal(true);
    playSound("what-do-you-want");
  };

  const handleSave = async () => {
    mutationGuard.current = true;
    try {
      if (editing) {
        await updateFeature.mutateAsync({
          id: editing.id,
          data: {
            name: form.name,
            description: form.description,
            status: form.status as Feature["status"],
          },
        });
      } else {
        await createFeature.mutateAsync(form);
      }
      setShowModal(false);
    } catch {
      // error sound played by hook
    }
  };

  const handleDelete = async (fId: number) => {
    mutationGuard.current = true;
    try {
      await deleteFeature.mutateAsync(fId);
    } catch {
      // error sound played by hook
    }
  };

  const mutationError = createFeature.error || updateFeature.error;
  const errorMessage = mutationError instanceof Error ? mutationError.message : mutationError ? "Failed" : "";

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <h1 className="flex items-center gap-3 text-2xl font-bold">
          <img src="/scroll.webp" alt="" className="h-8 w-8 rounded" />
          Features
        </h1>
        <button
          onClick={openCreate}
          className="rounded bg-[#5fa33a] px-4 py-2 text-sm font-medium text-black hover:bg-[#4d8a2e]"
        >
          New Feature
        </button>
      </div>

      <div className="mb-4 flex gap-2">
        <button
          onClick={() => setFilterStatus("")}
          className={`rounded px-3 py-1 text-sm ${!filterStatus ? "bg-[#2e3625] text-[#d4d2c4]" : "text-[#8a8672] hover:text-[#d4d2c4]"}`}
        >
          All
        </button>
        {STATUSES.map((s) => (
          <button
            key={s}
            onClick={() => setFilterStatus(s)}
            className={`rounded px-3 py-1 text-sm ${filterStatus === s ? "bg-[#2e3625] text-[#d4d2c4]" : "text-[#8a8672] hover:text-[#d4d2c4]"}`}
          >
            {s.replace("_", " ")}
          </button>
        ))}
      </div>

      {features.length === 0 ? (
        <p className="text-[#8a8672]">No features found.</p>
      ) : (
        <div className="overflow-hidden rounded-lg border border-[#2e3625]">
          <table className="w-full text-left text-sm">
            <thead className="border-b border-[#2e3625] bg-[#0d0f0a]">
              <tr>
                <th className="px-4 py-3 font-medium text-[#8a8672]">Name</th>
                <th className="px-4 py-3 font-medium text-[#8a8672]">Status</th>
                <th className="px-4 py-3 font-medium text-[#8a8672]">Updated</th>
                <th className="px-4 py-3 font-medium text-[#8a8672]"></th>
              </tr>
            </thead>
            <tbody>
              {features.map((f) => (
                <tr
                  key={f.id}
                  className="border-b border-[#2e3625] bg-[#1a1f14] hover:bg-[#242b1c]"
                >
                  <td className="px-4 py-3">
                    <div>
                      <span className="font-medium">{f.name}</span>
                      {f.description && (
                        <p className="mt-0.5 truncate text-xs text-[#8a8672]">
                          {f.description}
                        </p>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <StatusBadge status={f.status} />
                  </td>
                  <td className="px-4 py-3 text-[#8a8672]">
                    {new Date(f.updated_at).toLocaleDateString()}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex gap-2">
                      <button
                        onClick={() => openEdit(f)}
                        className="text-xs text-[#8a8672] hover:text-[#d4d2c4]"
                      >
                        Edit
                      </button>
                      <button
                        onClick={() => handleDelete(f.id)}
                        className="text-xs text-red-400 hover:text-red-300"
                      >
                        Delete
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <Modal
        open={showModal}
        onClose={() => setShowModal(false)}
        title={editing ? "Edit Feature" : "New Feature"}
      >
        <div className="space-y-4">
          <div>
            <label className="mb-1 block text-sm text-[#8a8672]">Name</label>
            <input
              value={form.name}
              onChange={(e) => setForm({ ...form, name: e.target.value })}
              className="w-full rounded border border-[#2e3625] bg-[#1a1f14] px-3 py-2 text-sm text-[#d4d2c4] placeholder-[#5c5a4a] focus:border-[#5c5a4a] focus:outline-none"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm text-[#8a8672]">
              Description
            </label>
            <textarea
              value={form.description}
              onChange={(e) =>
                setForm({ ...form, description: e.target.value })
              }
              rows={3}
              className="w-full rounded border border-[#2e3625] bg-[#1a1f14] px-3 py-2 text-sm text-[#d4d2c4] placeholder-[#5c5a4a] focus:border-[#5c5a4a] focus:outline-none"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm text-[#8a8672]">Status</label>
            <select
              value={form.status}
              onChange={(e) => setForm({ ...form, status: e.target.value })}
              className="w-full rounded border border-[#2e3625] bg-[#1a1f14] px-3 py-2 text-sm text-[#d4d2c4] focus:border-[#5c5a4a] focus:outline-none"
            >
              {STATUSES.map((s) => (
                <option key={s} value={s}>
                  {s.replace("_", " ")}
                </option>
              ))}
            </select>
          </div>
          {errorMessage && <p className="text-sm text-red-400">{errorMessage}</p>}
          <button
            onClick={handleSave}
            disabled={!form.name.trim()}
            className="w-full rounded bg-[#5fa33a] px-4 py-2 text-sm font-medium text-black hover:bg-[#4d8a2e] disabled:opacity-50"
          >
            {editing ? "Update" : "Create"}
          </button>
        </div>
      </Modal>
    </div>
  );
}
