"use client";

import { useState, useMemo } from "react";
import type { AutomergeUrl } from "@automerge/automerge-repo";
import { useDocument } from "@automerge/automerge-repo-react-hooks";
import { addOption, vote, unvote, hasVoted } from "../lib/poll.js";
import { getPeerId } from "../lib/peer.js";
import type { Poll } from "../lib/types.js";
import ConnectionStatus from "./ConnectionStatus.js";

export default function PollView({ docUrl }: { docUrl: AutomergeUrl }) {
  const [doc, changeDoc] = useDocument<Poll>(docUrl);
  const [newOption, setNewOption] = useState("");
  const [copied, setCopied] = useState(false);
  const peerId = useMemo(() => getPeerId(), []);

  if (!doc) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-gray-500">Loading poll...</div>
      </div>
    );
  }

  const totalVotes = doc.options.reduce((sum, o) => sum + o.votes.length, 0);

  const handleAddOption = () => {
    const text = newOption.trim();
    if (!text) return;
    changeDoc((d) => addOption(d, text));
    setNewOption("");
  };

  const handleVote = (optionId: string) => {
    if (hasVoted(doc, optionId, peerId)) {
      changeDoc((d) => unvote(d, optionId, peerId));
    } else {
      changeDoc((d) => vote(d, optionId, peerId));
    }
  };

  const handleCopy = () => {
    const url = window.location.href;
    navigator.clipboard.writeText(url).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }).catch(() => {});
  };

  return (
    <div className="space-y-6">
      <div className="flex items-start justify-between">
        <div>
          <h2 className="text-2xl font-bold">{doc.title}</h2>
          <p className="mt-1 text-sm text-gray-500">
            {totalVotes} vote{totalVotes !== 1 ? "s" : ""} total
          </p>
        </div>
        <ConnectionStatus />
      </div>

      {/* Options list */}
      <div className="space-y-3">
        {doc.options.map((option) => {
          const voted = hasVoted(doc, option.id, peerId);
          const pct = totalVotes > 0 ? (option.votes.length / totalVotes) * 100 : 0;

          return (
            <div
              key={option.id}
              className="relative overflow-hidden rounded-lg border border-gray-200 bg-white"
            >
              {/* Vote bar */}
              <div
                className="absolute inset-y-0 left-0 bg-blue-50 transition-all duration-300"
                style={{ width: `${pct}%` }}
              />
              <div className="relative flex items-center justify-between px-4 py-3">
                <button
                  onClick={() => handleVote(option.id)}
                  className={`flex items-center gap-2 text-left text-sm font-medium ${
                    voted ? "text-blue-600" : "text-gray-700 hover:text-blue-600"
                  }`}
                >
                  <span
                    className={`flex h-5 w-5 items-center justify-center rounded border text-xs ${
                      voted
                        ? "border-blue-600 bg-blue-600 text-white"
                        : "border-gray-300"
                    }`}
                  >
                    {voted ? "\u2713" : ""}
                  </span>
                  {option.text}
                </button>
                <span className="text-sm text-gray-500">
                  {option.votes.length} ({pct.toFixed(0)}%)
                </span>
              </div>
            </div>
          );
        })}

        {doc.options.length === 0 && (
          <p className="py-4 text-center text-sm text-gray-400">
            No options yet. Add one below!
          </p>
        )}
      </div>

      {/* Add option form */}
      <div className="flex gap-2">
        <input
          type="text"
          value={newOption}
          onChange={(e) => setNewOption(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && handleAddOption()}
          placeholder="Add an option..."
          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={handleAddOption}
          className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
        >
          Add
        </button>
      </div>

      {/* Share */}
      <div className="border-t border-gray-200 pt-4">
        <button
          onClick={handleCopy}
          className="rounded-md border border-gray-300 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50"
        >
          {copied ? "Copied!" : "Copy shareable link"}
        </button>
      </div>
    </div>
  );
}
