import { useState, useRef } from "react";
import { useParams } from "react-router-dom";
import {
  useTaskList,
  useCreateTask,
  useUpdateTask,
  useDeleteTask,
} from "../hooks/useTasks";
import { useExternalChangeSound } from "../hooks/useExternalChangeSound";
import type { Task } from "../types";
import StatusBadge from "./StatusBadge";
import PriorityBadge from "./PriorityBadge";
import Modal from "./Modal";
import { playSound } from "../usePeonSounds";

const STATUSES = ["todo", "in_progress", "done", "cancelled"] as const;
const PRIORITIES = ["critical", "high", "medium", "low"] as const;

export default function TasksPage() {
  const { id: projectId } = useParams<{ id: string }>();
  const [filterStatus, setFilterStatus] = useState("");
  const [filterPriority, setFilterPriority] = useState("");
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState<Task | null>(null);
  const [form, setForm] = useState({
    title: "",
    description: "",
    priority: "medium",
    status: "todo",
    commit_base: "",
    commit_head: "",
  });

  const mutationGuard = useRef(false);
  const { data: tasks = [] } = useTaskList(
    projectId,
    filterStatus || undefined,
    filterPriority || undefined
  );
  const createTask = useCreateTask(projectId!);
  const updateTask = useUpdateTask(projectId!);
  const deleteTask = useDeleteTask(projectId!);

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

  const openCreate = () => {
    setEditing(null);
    setForm({ title: "", description: "", priority: "medium", status: "todo", commit_base: "", commit_head: "" });
    setShowModal(true);
    playSound("what-do-you-want");
  };

  const openEdit = (t: Task) => {
    setEditing(t);
    setForm({
      title: t.title,
      description: t.description,
      priority: t.priority,
      status: t.status,
      commit_base: t.commit_base,
      commit_head: t.commit_head,
    });
    setShowModal(true);
    playSound("what-do-you-want");
  };

  const handleSave = async () => {
    mutationGuard.current = true;
    try {
      if (editing) {
        await updateTask.mutateAsync({
          id: editing.id,
          data: {
            title: form.title,
            description: form.description,
            priority: form.priority as Task["priority"],
            status: form.status as Task["status"],
            commit_base: form.commit_base,
            commit_head: form.commit_head,
          },
        });
      } else {
        await createTask.mutateAsync({
          ...form,
          commit_base: form.commit_base || undefined,
          commit_head: form.commit_head || undefined,
        });
      }
      setShowModal(false);
    } catch {
      // error sound played by hook
    }
  };

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

  const mutationError = createTask.error || updateTask.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="/shield.webp" alt="" className="h-8 w-8 rounded" />
          Tasks
        </h1>
        <button
          onClick={openCreate}
          className="rounded bg-[#5fa33a] px-4 py-2 text-sm font-medium text-black hover:bg-[#4d8a2e]"
        >
          New Task
        </button>
      </div>

      <div className="mb-4 flex flex-wrap gap-4">
        <div className="flex gap-2">
          <span className="self-center text-xs text-[#8a8672]">Status:</span>
          <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>
        <div className="flex gap-2">
          <span className="self-center text-xs text-[#8a8672]">Priority:</span>
          <button
            onClick={() => setFilterPriority("")}
            className={`rounded px-3 py-1 text-sm ${!filterPriority ? "bg-[#2e3625] text-[#d4d2c4]" : "text-[#8a8672] hover:text-[#d4d2c4]"}`}
          >
            All
          </button>
          {PRIORITIES.map((p) => (
            <button
              key={p}
              onClick={() => setFilterPriority(p)}
              className={`rounded px-3 py-1 text-sm ${filterPriority === p ? "bg-[#2e3625] text-[#d4d2c4]" : "text-[#8a8672] hover:text-[#d4d2c4]"}`}
            >
              {p}
            </button>
          ))}
        </div>
      </div>

      {tasks.length === 0 ? (
        <p className="text-[#8a8672]">No tasks 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="w-2/5 px-4 py-3 font-medium text-[#8a8672]">Title</th>
                <th className="px-4 py-3 font-medium text-[#8a8672]">Priority</th>
                <th className="px-4 py-3 font-medium text-[#8a8672]">Status</th>
                <th className="px-4 py-3 font-medium text-[#8a8672]">Commits</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>
              {tasks.map((t) => (
                <tr
                  key={t.id}
                  className="border-b border-[#2e3625] bg-[#1a1f14] hover:bg-[#242b1c]"
                >
                  <td className="max-w-0 px-4 py-3">
                    <div className="overflow-hidden">
                      <span className="block truncate font-medium">{t.title}</span>
                      {t.description && (
                        <p className="mt-0.5 truncate text-xs text-[#8a8672]">
                          {t.description}
                        </p>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <PriorityBadge priority={t.priority} />
                  </td>
                  <td className="px-4 py-3">
                    <StatusBadge status={t.status} />
                  </td>
                  <td className="px-4 py-3">
                    {(t.commit_base || t.commit_head) ? (
                      <div className="flex gap-1 font-mono text-xs text-[#8a8672]">
                        {t.commit_base && <span title={t.commit_base}>{t.commit_base.slice(0, 8)}</span>}
                        {t.commit_base && t.commit_head && <span>..</span>}
                        {t.commit_head && <span title={t.commit_head}>{t.commit_head.slice(0, 8)}</span>}
                      </div>
                    ) : (
                      <span className="text-xs text-[#5c5a4a]">--</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-[#8a8672]">
                    {new Date(t.updated_at).toLocaleDateString()}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex gap-2">
                      <button
                        onClick={() => openEdit(t)}
                        className="text-xs text-[#8a8672] hover:text-[#d4d2c4]"
                      >
                        Edit
                      </button>
                      <button
                        onClick={() => handleDelete(t.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 Task" : "New Task"}
      >
        <div className="space-y-4">
          <div>
            <label className="mb-1 block text-sm text-[#8a8672]">Title</label>
            <input
              value={form.title}
              onChange={(e) => setForm({ ...form, title: 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 className="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1 block text-sm text-[#8a8672]">
                Priority
              </label>
              <select
                value={form.priority}
                onChange={(e) =>
                  setForm({ ...form, priority: 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"
              >
                {PRIORITIES.map((p) => (
                  <option key={p} value={p}>
                    {p}
                  </option>
                ))}
              </select>
            </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>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1 block text-sm text-[#8a8672]">
                Base Commit
              </label>
              <input
                value={form.commit_base}
                onChange={(e) =>
                  setForm({ ...form, commit_base: e.target.value })
                }
                placeholder="SHA"
                className="w-full rounded border border-[#2e3625] bg-[#1a1f14] px-3 py-2 font-mono text-sm text-[#d4d2c4] placeholder-[#5c5a4a] focus:border-[#5c5a4a] focus:outline-none"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm text-[#8a8672]">
                Head Commit
              </label>
              <input
                value={form.commit_head}
                onChange={(e) =>
                  setForm({ ...form, commit_head: e.target.value })
                }
                placeholder="SHA"
                className="w-full rounded border border-[#2e3625] bg-[#1a1f14] px-3 py-2 font-mono text-sm text-[#d4d2c4] placeholder-[#5c5a4a] focus:border-[#5c5a4a] focus:outline-none"
              />
            </div>
          </div>
          {errorMessage && <p className="text-sm text-red-400">{errorMessage}</p>}
          <button
            onClick={handleSave}
            disabled={!form.title.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>
  );
}
