import { useState, useRef } from "react";
import { useParams } from "react-router-dom";
import { useWorkLogList, useCreateWorkLog } from "../hooks/useWorkLogs";
import { useTaskList } from "../hooks/useTasks";
import { useExternalChangeSound } from "../hooks/useExternalChangeSound";
import Modal from "./Modal";
import { playSound } from "../usePeonSounds";

export default function WorkLogsPage() {
  const { id: projectId } = useParams<{ id: string }>();
  const [showModal, setShowModal] = useState(false);
  const [form, setForm] = useState({
    task_id: "",
    summary: "",
    files_changed: "",
    test_result: "",
  });

  const mutationGuard = useRef(false);
  const { data: logs = [] } = useWorkLogList(projectId);
  const { data: tasks = [] } = useTaskList(projectId);
  const createWorkLog = useCreateWorkLog(projectId!);

  useExternalChangeSound(logs, "double", mutationGuard);

  const openCreate = () => {
    setForm({ task_id: "", summary: "", files_changed: "", test_result: "" });
    setShowModal(true);
    playSound("what-do-you-want");
  };

  const handleSave = async () => {
    mutationGuard.current = true;
    try {
      await createWorkLog.mutateAsync({
        task_id: parseInt(form.task_id),
        summary: form.summary,
        files_changed: form.files_changed,
        test_result: form.test_result,
      });
      setShowModal(false);
    } catch {
      // error sound played by hook
    }
  };

  const errorMessage =
    createWorkLog.error instanceof Error
      ? createWorkLog.error.message
      : createWorkLog.error
        ? "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="/project.webp" alt="" className="h-8 w-8 rounded" />
          Work Logs
        </h1>
        <button
          onClick={openCreate}
          className="rounded bg-[#5fa33a] px-4 py-2 text-sm font-medium text-black hover:bg-[#4d8a2e]"
        >
          Log Work
        </button>
      </div>

      {logs.length === 0 ? (
        <p className="text-[#8a8672]">No work logs yet.</p>
      ) : (
        <div className="space-y-3">
          {logs.map((log) => (
            <div
              key={log.id}
              className="rounded-lg border border-[#2e3625] bg-[#1a1f14] p-4"
            >
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <p className="text-sm">{log.summary}</p>
                  {log.files_changed && (
                    <p className="mt-1 text-xs text-[#8a8672]">
                      Files: {log.files_changed}
                    </p>
                  )}
                </div>
                {log.test_result && (
                  <span
                    className={`ml-3 inline-block rounded-full px-2.5 py-0.5 text-xs font-medium ${
                      log.test_result === "pass"
                        ? "bg-emerald-900 text-emerald-300"
                        : log.test_result === "fail"
                          ? "bg-red-900 text-red-300"
                          : "bg-gray-800 text-gray-400"
                    }`}
                  >
                    {log.test_result}
                  </span>
                )}
              </div>
              <div className="mt-2 flex items-center gap-3 text-xs text-[#5c5a4a]">
                <span>Task #{log.task_id}</span>
                <span>{new Date(log.created_at).toLocaleString()}</span>
              </div>
            </div>
          ))}
        </div>
      )}

      <Modal
        open={showModal}
        onClose={() => setShowModal(false)}
        title="Log Work"
      >
        <div className="space-y-4">
          <div>
            <label className="mb-1 block text-sm text-[#8a8672]">Task</label>
            <select
              value={form.task_id}
              onChange={(e) => setForm({ ...form, task_id: 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"
            >
              <option value="">Select a task...</option>
              {tasks.map((t) => (
                <option key={t.id} value={t.id}>
                  #{t.id} — {t.title}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="mb-1 block text-sm text-[#8a8672]">Summary</label>
            <textarea
              value={form.summary}
              onChange={(e) => setForm({ ...form, summary: 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]">
              Files Changed
            </label>
            <input
              value={form.files_changed}
              onChange={(e) =>
                setForm({ ...form, files_changed: e.target.value })
              }
              placeholder="e.g. src/app.ts, README.md"
              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]">
              Test Result
            </label>
            <select
              value={form.test_result}
              onChange={(e) =>
                setForm({ ...form, test_result: 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"
            >
              <option value="">N/A</option>
              <option value="pass">Pass</option>
              <option value="fail">Fail</option>
              <option value="skip">Skip</option>
            </select>
          </div>
          {errorMessage && <p className="text-sm text-red-400">{errorMessage}</p>}
          <button
            onClick={handleSave}
            disabled={!form.task_id || !form.summary.trim()}
            className="w-full rounded bg-[#5fa33a] px-4 py-2 text-sm font-medium text-black hover:bg-[#4d8a2e] disabled:opacity-50"
          >
            Save Log
          </button>
        </div>
      </Modal>
    </div>
  );
}
