"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import type { Poll } from "@/types";

interface VoteFormProps {
  poll: Poll;
}

export default function VoteForm({ poll }: VoteFormProps) {
  const [selectedOption, setSelectedOption] = useState<number | null>(null);
  const [hasVoted, setHasVoted] = useState<boolean>(false);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const [currentPoll, setCurrentPoll] = useState<Poll>(poll);
  const router = useRouter();

  const totalVotes: number = currentPoll.votes.reduce(
    (sum, v) => sum + v,
    0
  );

  async function handleVote(): Promise<void> {
    if (selectedOption === null || isSubmitting) return;

    setIsSubmitting(true);

    const response = await fetch(`/api/polls/${currentPoll.id}/vote`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ optionIndex: selectedOption }),
    });

    if (response.ok) {
      const updatedPoll: Poll = await response.json();
      setCurrentPoll(updatedPoll);
      setHasVoted(true);
    }

    setIsSubmitting(false);
  }

  function getPercentage(votes: number): number {
    if (totalVotes === 0) return 0;
    return Math.round((votes / totalVotes) * 100);
  }

  return (
    <div className="space-y-3">
      {currentPoll.options.map((option, index) => {
        const percentage = getPercentage(currentPoll.votes[index]);
        const isSelected = selectedOption === index;

        return (
          <button
            key={index}
            onClick={() => !hasVoted && setSelectedOption(index)}
            disabled={hasVoted}
            className={`w-full text-left p-4 rounded-lg border-2 transition-all relative overflow-hidden ${
              hasVoted
                ? "border-gray-200 cursor-default"
                : isSelected
                  ? "border-purple-500 bg-purple-50"
                  : "border-gray-200 hover:border-purple-300 cursor-pointer"
            }`}
          >
            {hasVoted && (
              <div
                className="absolute inset-0 bg-purple-100 transition-all duration-500"
                style={{ width: `${percentage}%` }}
              />
            )}
            <div className="relative flex justify-between items-center">
              <div className="flex items-center gap-3">
                {!hasVoted && (
                  <div
                    className={`w-5 h-5 rounded-full border-2 flex items-center justify-center ${
                      isSelected
                        ? "border-purple-500 bg-purple-500"
                        : "border-gray-300"
                    }`}
                  >
                    {isSelected && (
                      <div className="w-2 h-2 rounded-full bg-white" />
                    )}
                  </div>
                )}
                <span className="font-medium">{option}</span>
              </div>
              {hasVoted && (
                <span className="text-sm font-semibold text-purple-700">
                  {percentage}% ({currentPoll.votes[index]} stemmen)
                </span>
              )}
            </div>
          </button>
        );
      })}

      {!hasVoted && (
        <button
          onClick={handleVote}
          disabled={selectedOption === null || isSubmitting}
          className="w-full bg-purple-600 text-white py-3 rounded-lg font-medium hover:bg-purple-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors mt-4"
        >
          {isSubmitting ? "Bezig met stemmen..." : "Stem!"}
        </button>
      )}

      {hasVoted && (
        <div className="text-center pt-4">
          <p className="text-green-600 font-medium mb-2">
            Bedankt voor je stem!
          </p>
          <p className="text-sm text-gray-500">
            Totaal: {totalVotes} stemmen
          </p>
          <button
            onClick={() => router.push("/")}
            className="mt-4 text-purple-600 hover:underline text-sm"
          >
            ← Terug naar alle polls
          </button>
        </div>
      )}
    </div>
  );
}
