"use client";

import { useState } from "react";
import Link from "next/link";
import type { Poll } from "@/types";

interface VoteFormProps {
  poll: Poll;
}

// STAP 6: VoteForm — de stem interface
//
// Dit is een CLIENT component ("use client" staat bovenaan).
// Hier mag je wel useState en onClick gebruiken!
//
// Benodigde state:
// - selectedOption: number | null (welke optie is geselecteerd)
// - hasVoted: boolean (heeft de gebruiker al gestemd)
// - isLoading: boolean (wordt het formulier verstuurd)
// - currentPoll: Poll (de huidige poll data, update na stemmen)
//
// Wat moet je bouwen?
// 1. Toon alle opties als klikbare knoppen (voor het stemmen)
// 2. Highlight de geselecteerde optie met purple border
// 3. Een "Stem!" knop die een POST doet naar /api/polls/{id}/vote
// 4. Na het stemmen: toon de resultaten met progress bars en percentages
// 5. Toon een "Terug" link naar de homepage

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

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

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

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

    try {
      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);
      }
    } finally {
      setIsLoading(false);
    }
  }

  // Nog niet gestemd — toon opties
  if (!hasVoted) {
    return (
      <div className="space-y-4">
        {currentPoll.options.map((option, idx) => (
          <button
            key={idx}
            onClick={() => setSelectedOption(idx)}
            disabled={isLoading}
            className={`w-full text-left p-4 rounded-lg border-2 transition ${
              selectedOption === idx
                ? "border-purple-500 bg-purple-50"
                : "border-gray-200 hover:border-purple-300"
            }`}
          >
            <span className="font-medium">{option}</span>
          </button>
        ))}

        <button
          onClick={handleVote}
          disabled={selectedOption === null || isLoading}
          className="w-full bg-purple-600 text-white py-3 rounded-lg hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition font-medium"
        >
          {isLoading ? "Aan het stemmen..." : "Stem!"}
        </button>
      </div>
    );
  }

  // Wel gestemd — toon resultaten
  return (
    <div className="space-y-6">
      <p className="text-green-600 font-medium text-lg">
        ✓ Bedankt voor je stem!
      </p>

      <div className="space-y-4">
        {currentPoll.options.map((option, idx) => (
          <div key={idx}>
            <div className="flex justify-between mb-2">
              <span className="font-medium">{option}</span>
              <span className="text-sm text-gray-600">
                {currentPoll.votes[idx]} stemmen ({getPercentage(currentPoll.votes[idx])}%)
              </span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-3">
              <div
                className="bg-purple-600 h-3 rounded-full transition-all"
                style={{
                  width: `${getPercentage(currentPoll.votes[idx])}%`,
                }}
              />
            </div>
          </div>
        ))}
      </div>

      <Link
        href="/"
        className="block text-center text-purple-600 hover:underline mt-6"
      >
        ← Terug naar polls
      </Link>
    </div>
  );
}
