"use client";

import { useState } from "react";
import { useRouter } from "waku";
import { useRepo } from "@automerge/automerge-repo-react-hooks";
import { createPoll } from "../lib/poll.js";
import type { Poll } from "../lib/types.js";

export default function HomeClient() {
  const [title, setTitle] = useState("");
  const [joinId, setJoinId] = useState("");
  const repo = useRepo();
  const router = useRouter();

  const handleCreate = () => {
    if (!title.trim()) return;
    const handle = repo.create<Poll>();
    handle.change((doc) => {
      const poll = createPoll(title.trim());
      doc.title = poll.title;
      doc.options = poll.options;
    });
    router.push(`/poll/${handle.documentId}`);
  };

  const handleJoin = () => {
    const id = joinId.trim();
    if (!id) return;
    router.push(`/poll/${id}`);
  };

  return (
    <div className="space-y-8">
      <title>P2P Poll</title>

      {/* Create Poll */}
      <section className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm">
        <h2 className="mb-4 text-lg font-semibold">Create a New Poll</h2>
        <div className="flex gap-2">
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleCreate()}
            placeholder="Enter poll title..."
            className="flex-1 rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
          />
          <button
            onClick={handleCreate}
            className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
          >
            Create
          </button>
        </div>
      </section>

      {/* Join Poll */}
      <section className="rounded-lg border border-gray-200 bg-white p-6 shadow-sm">
        <h2 className="mb-4 text-lg font-semibold">Join an Existing Poll</h2>
        <div className="flex gap-2">
          <input
            type="text"
            value={joinId}
            onChange={(e) => setJoinId(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleJoin()}
            placeholder="Paste poll ID or link..."
            className="flex-1 rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
          />
          <button
            onClick={handleJoin}
            className="rounded-md bg-gray-600 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
          >
            Join
          </button>
        </div>
      </section>
    </div>
  );
}
