'use client';

import { Chart, registerables, TooltipItem } from 'chart.js';
import { useEffect, useRef, useState } from 'react';
import { getActivePoll } from '@/lib/db/dashboard';

// Register Chart.js components
Chart.register(...registerables);

const PolingSection = () => {
  const poll = getActivePoll();
  const chartRef = useRef<HTMLCanvasElement>(null);
  const chartInstanceRef = useRef<Chart | null>(null);
  const [selectedOption, setSelectedOption] = useState<string>('');
  const [hasVoted, setHasVoted] = useState(false);
  const [totalVotes, setTotalVotes] = useState(poll.totalVotes);

  const pollOptions = poll.options;

  // Convert to Bengali numerals
  const toBengali = (num: number | string): string => {
    const bengaliNumerals = ['০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯'];
    return num
      .toString()
      .split('')
      .map((digit) => {
        if (digit === '.' || digit === ',') return digit;
        const digitNum = parseInt(digit);
        return isNaN(digitNum) ? digit : bengaliNumerals[digitNum];
      })
      .join('');
  };

  // Format number with commas and convert to Bengali
  const formatBengaliNumber = (num: number): string => {
    return toBengali(num.toLocaleString('en-US'));
  };

  // Initialize Chart
  useEffect(() => {
    if (!chartRef.current) return;

    // Destroy existing chart if it exists
    if (chartInstanceRef.current) {
      chartInstanceRef.current.destroy();
    }

    const ctx = chartRef.current.getContext('2d');
    if (!ctx) return;

    chartInstanceRef.current = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ['খুবই আস্থাশীল', 'মোটামুটি আস্থাশীল', 'আস্থা নেই', 'মন্তব্য নেই'],
        datasets: [
          {
            label: 'ভোটের হার (%)',
            data: [45, 30, 15, 10],
            backgroundColor: [
              '#2563eb', // blue-600
              '#60a5fa', // blue-400
              '#ef4444', // red-500
              '#9ca3af', // gray-400
            ],
            borderRadius: 6,
            barThickness: 30,
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false },
          tooltip: {
            callbacks: {
              label: (context: TooltipItem<'bar'>) => ` ${toBengali(context.parsed.y ?? 0)}%`,
            },
            titleFont: { family: "'Hind Siliguri', sans-serif" },
            bodyFont: { family: "'Hind Siliguri', sans-serif" },
          },
        },
        scales: {
          y: {
            beginAtZero: true,
            max: 60,
            grid: { color: '#f3f4f6' },
            ticks: {
              font: { family: "'Hind Siliguri', sans-serif" },
              callback: (value: string | number) => toBengali(value) + '%',
            },
          },
          x: {
            grid: { display: false },
            ticks: {
              font: { family: "'Hind Siliguri', sans-serif", size: 11, weight: 600 },
            },
          },
        },
      },
    });

    // Cleanup
    return () => {
      if (chartInstanceRef.current) {
        chartInstanceRef.current.destroy();
      }
    };
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedOption) {
      alert('অনুগ্রহ করে একটি অপশন নির্বাচন করুন');
      return;
    }
    setHasVoted(true);
    setTotalVotes((prev) => prev + 1);
  };

  const handleVoteAgain = () => {
    setHasVoted(false);
    setSelectedOption('');
  };

  return (
    <section id="polling-section" className="py-16 bg-gray-50 border-t border-gray-200">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-12">
          <span className="text-blue-600 font-bold tracking-wider uppercase text-sm">
            জনমত জরিপ
          </span>
          <h2 className="text-3xl md:text-4xl font-bold text-gray-900 mt-2">
            আপনার মতামত গুরুত্বপূর্ণ
          </h2>
          <div className="w-20 h-1 bg-yellow-500 mx-auto mt-4 rounded"></div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-10">
          <div
            id="active-poll"
            className="bg-white rounded-3xl shadow-xl border border-gray-100 overflow-hidden"
          >
            <div className="bg-blue-600 p-6 text-white">
              <div className="flex items-center gap-3 mb-2">
                <span className="material-symbols-outlined animate-pulse">live_help</span>
                <span className="bg-red-500 text-white text-xs font-bold px-2 py-1 rounded uppercase">
                  Active
                </span>
              </div>
              <h3 className="text-xl md:text-2xl font-bold">{poll.question}</h3>
              <p className="text-blue-100 text-sm mt-2">
                মোট ভোট: <span id="total-votes-count">{formatBengaliNumber(totalVotes)}</span>
              </p>
            </div>

            <div className="p-6 md:p-8">
              {!hasVoted ? (
                <form id="poll-form" className="space-y-4" onSubmit={handleSubmit}>
                  {pollOptions.map((option) => (
                    <label key={option.value} className="block relative group cursor-pointer">
                      <input
                        type="radio"
                        name="poll_option"
                        value={option.value}
                        className="peer sr-only"
                        checked={selectedOption === option.value}
                        onChange={(e) => setSelectedOption(e.target.value)}
                      />
                      <div className="p-4 rounded-xl border-2 border-gray-200 peer-checked:border-blue-600 peer-checked:bg-blue-50 transition flex items-center justify-between group-hover:border-blue-300">
                        <span className="font-bold text-gray-700 peer-checked:text-blue-900">
                          {option.label}
                        </span>
                        <span className="w-6 h-6 border-2 border-gray-300 rounded flex items-center justify-center peer-checked:border-blue-600 peer-checked:after:content-[''] peer-checked:after:w-3 peer-checked:after:h-3 peer-checked:after:bg-blue-600 peer-checked:after:rounded"></span>
                      </div>
                    </label>
                  ))}

                  <button
                    type="submit"
                    className="w-full bg-blue-600 text-white py-4 rounded-xl font-bold text-lg shadow-lg hover:bg-blue-700 transform active:scale-95 transition-all mt-4"
                  >
                    ভোট দিন
                  </button>
                </form>
              ) : (
                <div id="poll-results" className="space-y-4">
                  <h4 className="font-bold text-gray-900 text-center mb-6">ফলাফল:</h4>
                  <div className="space-y-3">
                    {pollOptions.map((option, index) => {
                      const percentages = [35, 28, 22, 15]; // Example percentages
                      const percentage = percentages[index];
                      return (
                        <div key={option.value} className="space-y-2">
                          <div className="flex justify-between items-center">
                            <span className="text-sm font-medium text-gray-700">
                              {option.label}
                            </span>
                            <span className="text-sm font-bold text-blue-600">
                              {toBengali(percentage)}%
                            </span>
                          </div>
                          <div className="w-full bg-gray-200 rounded-full h-2.5">
                            <div
                              className="bg-blue-600 h-2.5 rounded-full transition-all duration-500"
                              style={{ width: `${percentage}%` }}
                            ></div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                  <button
                    id="vote-again-btn"
                    onClick={handleVoteAgain}
                    className="w-full bg-gray-100 text-gray-600 py-3 rounded-xl font-bold text-sm hover:bg-gray-200 transition mt-6"
                  >
                    পুনরায় ভোট দিন
                  </button>
                </div>
              )}
            </div>
          </div>

          <div className="flex flex-col gap-6">
            <div className="bg-white rounded-3xl shadow-sm border border-blue-100 p-6">
              <h3 className="font-bold text-blue-900 text-xl mb-4 flex items-center gap-2">
                <span className="material-symbols-outlined text-blue-500">poll</span>
                বিগত সপ্তাহের জরিপ ফলাফল
              </h3>
              <p className="text-sm text-gray-500 mb-4">
                প্রশ্ন: বর্তমান নির্বাচন কমিশনের ওপর আপনার আস্থা কতটুকু?
              </p>
              <div className="h-64">
                <canvas ref={chartRef} id="previousPollChart"></canvas>
              </div>
            </div>

            <div className="bg-white rounded-3xl shadow-sm border border-blue-100 p-6 flex-1">
              <h3 className="font-bold text-blue-900 text-xl mb-4 flex items-center gap-2">
                <span className="material-symbols-outlined text-blue-500">history</span>
                আরও আর্কাইভ
              </h3>
              <div className="space-y-4">
                <div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl hover:bg-blue-50 transition cursor-pointer">
                  <div>
                    <h5 className="font-bold text-gray-800 text-sm">
                      ডিজিটাল নিরাপত্তা আইন সংস্কার প্রয়োজন?
                    </h5>
                    <p className="text-xs text-gray-500 mt-1">তারিখ: ১ জানুয়ারি ২০২৬</p>
                  </div>
                  <span className="material-symbols-outlined text-gray-400">arrow_forward_ios</span>
                </div>
                <div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl hover:bg-blue-50 transition cursor-pointer">
                  <div>
                    <h5 className="font-bold text-gray-800 text-sm">
                      ইভিএম ব্যবহারে আপনার মতামত কী?
                    </h5>
                    <p className="text-xs text-gray-500 mt-1">তারিখ: ১৫ ডিসেম্বর ২০২৫</p>
                  </div>
                  <span className="material-symbols-outlined text-gray-400">arrow_forward_ios</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

export default PolingSection;
