import { useState } from "react";
import { useParams } from "wouter";
import { useLanguage } from "@/hooks/use-language";
import { useQuery } from "@tanstack/react-query";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Legend,
} from "recharts";
import type { Poll, PollQuestion, PollResponse } from "@shared/schema";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { format } from "date-fns";
import { Loader2 } from "lucide-react";

// Colors for charts
const COLORS = ['#2563eb', '#3b82f6', '#60a5fa', '#93c5fd', '#bfdbfe'];

export default function PollResultsPage() {
  const { t } = useLanguage();
  const params = useParams<{ id: string }>();
  const pollId = params?.id ? parseInt(params.id, 10) : null;

  // Initial render logging
  console.log("PollResultsPage - Initial Render", {
    params,
    pollId,
    timestamp: new Date().toISOString()
  });

  const pollQuery = useQuery<Poll>({
    queryKey: [`/api/polls/${pollId}`],
    queryFn: async () => {
      console.log("Fetching poll data for ID:", pollId);
      const response = await fetch(`/api/polls/${pollId}`);
      if (!response.ok) {
        const errorText = await response.text();
        console.error(`Failed to fetch poll: Status ${response.status}`, errorText);
        throw new Error(`Failed to fetch poll: ${response.statusText}`);
      }
      const data = await response.json();
      console.log("Poll data received:", data);
      return data;
    },
    enabled: !!pollId,
  });

  const questionsQuery = useQuery<PollQuestion[]>({
    queryKey: [`/api/polls/${pollId}/questions`],
    queryFn: async () => {
      console.log("Fetching questions for poll ID:", pollId);
      const response = await fetch(`/api/polls/${pollId}/questions`);
      if (!response.ok) {
        const errorText = await response.text();
        console.error(`Failed to fetch questions: Status ${response.status}`, errorText);
        throw new Error(`Failed to fetch questions: ${response.statusText}`);
      }
      const data = await response.json();
      console.log("Questions data received:", data);
      return data;
    },
    enabled: !!pollId,
  });

  const responsesQuery = useQuery<PollResponse[]>({
    queryKey: [`/api/polls/${pollId}/responses`],
    queryFn: async () => {
      console.log("Fetching responses for poll ID:", pollId);
      const response = await fetch(`/api/polls/${pollId}/responses`);
      if (!response.ok) {
        const errorText = await response.text();
        console.error(`Failed to fetch responses: Status ${response.status}`, errorText);
        throw new Error(`Failed to fetch responses: ${response.statusText}`);
      }
      const data = await response.json();
      console.log("Responses data received:", data);
      return data;
    },
    enabled: !!pollId,
  });

  if (pollQuery.isLoading || questionsQuery.isLoading || responsesQuery.isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="h-8 w-8 animate-spin mr-2" />
        <p>{t("Loading...", "جاري التحميل...")}</p>
      </div>
    );
  }

  if (pollQuery.isError || questionsQuery.isError || responsesQuery.isError) {
    return (
      <div className="flex items-center justify-center min-h-screen text-red-500">
        <div className="space-y-2">
          <p>{t("Error loading poll data", "خطأ في تحميل بيانات الاستطلاع")}</p>
          {pollQuery.error && (
            <p className="text-sm">Poll Error: {pollQuery.error.message}</p>
          )}
          {questionsQuery.error && (
            <p className="text-sm">Questions Error: {questionsQuery.error.message}</p>
          )}
          {responsesQuery.error && (
            <p className="text-sm">Responses Error: {responsesQuery.error.message}</p>
          )}
        </div>
      </div>
    );
  }

  const poll = pollQuery.data;
  const questions = questionsQuery.data;
  const responses = responsesQuery.data;

  if (!poll || !questions || !responses) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="space-y-2">
          <p>{t("No data available", "لا توجد بيانات متاحة")}</p>
          <p className="text-sm text-muted-foreground">
            Debug Info: Poll ID {pollId}
            {poll ? ` (Poll found)` : ' (No poll)'}
            {questions ? ` (${questions.length} questions)` : ' (No questions)'}
            {responses ? ` (${responses.length} responses)` : ' (No responses)'}
          </p>
        </div>
      </div>
    );
  }

  const renderQuestionResults = (question: PollQuestion) => {
    console.log("Rendering question:", question);

    const questionResponses = responses.filter(
      (r) => r.questionId === question.id
    );
    const totalResponses = questionResponses.length;

    if (totalResponses === 0) {
      return (
        <div className="text-center p-4 bg-muted rounded-lg">
          <p className="text-muted-foreground">
            {t("No responses yet", "لا توجد إجابات حتى الآن")}
          </p>
        </div>
      );
    }

    switch (question.pollTypeId) {
      case 1: // Range (1-5)
        const rangeData = Array(5)
          .fill(0)
          .map((_, i) => {
            // Check both numericResponse and textResponse for the value
            const count = questionResponses.filter(
              (r) => {
                const value = r.numericResponse || (r.textResponse ? parseInt(r.textResponse) : null);
                return value === i + 1;
              }
            ).length;
            return {
              rating: i + 1,
              count,
              percentage: ((count / totalResponses) * 100).toFixed(1)
            };
          });

        const average = questionResponses.reduce(
          (acc, r) => {
            const value = r.numericResponse || (r.textResponse ? parseInt(r.textResponse) : 0);
            return acc + (value || 0);
          },
          0
        ) / totalResponses;

        return (
          <div className="space-y-4">
            <div className="h-[300px]">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={rangeData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="rating" />
                  <YAxis />
                  <Tooltip
                    formatter={(value: number) => [
                      `${value} ${value === 1 ? t("response", "إجابة") : t("responses", "إجابات")} (${((value / totalResponses) * 100).toFixed(1)}%)`,
                      t("Responses", "الإجابات")
                    ]}
                  />
                  <Legend />
                  <Bar
                    name={t("Number of Responses", "عدد الإجابات")}
                    dataKey="count"
                    fill="#2563eb"
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>
            <div className="text-center space-y-2">
              <p className="text-lg font-medium">
                {t(
                  `Average Rating: ${average.toFixed(1)}`,
                  `متوسط التقييم: ${average.toFixed(1)}`
                )}
              </p>
              <p className="text-sm text-muted-foreground">
                {t(
                  `Total Responses: ${totalResponses}`,
                  `إجمالي الإجابات: ${totalResponses}`
                )}
              </p>
            </div>
          </div>
        );

      case 2: // YesNo
        const yesNoData = [
          {
            name: t("Yes", "نعم"),
            value: questionResponses.filter((r) => r.yesNoResponse === "yes").length,
          },
          {
            name: t("No", "لا"),
            value: questionResponses.filter((r) => r.yesNoResponse === "no").length,
          },
          {
            name: t("Maybe", "ربما"),
            value: questionResponses.filter((r) => r.yesNoResponse === "maybe").length,
          }
        ].map(item => ({
          ...item,
          percentage: ((item.value / totalResponses) * 100).toFixed(1)
        }));

        return (
          <div className="space-y-4">
            <div className="h-[300px]">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={yesNoData}
                    dataKey="value"
                    nameKey="name"
                    cx="50%"
                    cy="50%"
                    outerRadius={100}
                    label={({ name, percentage }) => `${name} (${percentage}%)`}
                  >
                    {yesNoData.map((_, index) => (
                      <Cell
                        key={`cell-${index}`}
                        fill={COLORS[index % COLORS.length]}
                      />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={(value: number, name: string) => [
                      `${value} ${value === 1 ? t("response", "إجابة") : t("responses", "إجابات")} (${((value / totalResponses) * 100).toFixed(1)}%)`,
                      name
                    ]}
                  />
                  <Legend />
                </PieChart>
              </ResponsiveContainer>
            </div>
            <p className="text-center text-sm text-muted-foreground">
              {t(
                `Total Responses: ${totalResponses}`,
                `إجمالي الإجابات: ${totalResponses}`
              )}
            </p>
          </div>
        );

      case 3: // MultipleChoice
      case 7: // MultipleChoicewithtext
        if (!question.options) return null;

        console.log('Processing question responses:', {
          questionId: question.id,
          responses: questionResponses,
          options: question.options
        });

        // Initialize counts for each option
        const optionCounts = {};
        question.options.forEach(option => {
          optionCounts[option] = { count: 0, percentage: '0' };
        });

        // Count responses for each option
        questionResponses.forEach(response => {
          if (Array.isArray(response.selectedOptions)) {
            response.selectedOptions.forEach(option => {
              if (optionCounts[option]) {
                optionCounts[option].count++;
              }
            });
          }
        });

        // Calculate percentages
        Object.keys(optionCounts).forEach(option => {
          optionCounts[option].percentage = 
            ((optionCounts[option].count / totalResponses) * 100).toFixed(1);
        });

        console.log('Option counts:', optionCounts);

        const multipleChoiceData = question.options.map(option => ({
          option,
          count: optionCounts[option].count,
          percentage: optionCounts[option].percentage
        }));

        return (
          <div className="space-y-4">
            <div className="h-[300px]">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={multipleChoiceData} layout="vertical">
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis type="number" />
                  <YAxis type="category" dataKey="option" width={150} />
                  <Tooltip
                    formatter={(value: number) => [
                      `${value} ${value === 1 ? t("response", "إجابة") : t("responses", "إجابات")} (${((value / totalResponses) * 100).toFixed(1)}%)`,
                      t("Responses", "الإجابات")
                    ]}
                  />
                  <Legend />
                  <Bar
                    name={t("Number of Responses", "عدد الإجابات")}
                    dataKey="count"
                    fill="#2563eb"
                  />
                </BarChart>
              </ResponsiveContainer>
            </div>

            {question.pollTypeId === 7 && (
              <div className="mt-4">
                <h4 className="font-medium mb-2">
                  {t("Other Responses", "إجابات أخرى")}
                </h4>
                <div className="space-y-2">
                  {questionResponses
                    .filter((r) => 
                      Array.isArray(r.selectedOptions) &&
                      r.selectedOptions.includes('Other') &&
                      r.textResponse
                    )
                    .map((r, i) => (
                      <div
                        key={i}
                        className="p-3 bg-muted rounded-lg text-sm"
                      >
                        {r.textResponse}
                      </div>
                    ))}
                </div>
              </div>
            )}

            <p className="text-center text-sm text-muted-foreground">
              {t(
                `Total Responses: ${totalResponses}`,
                `إجمالي الإجابات: ${totalResponses}`
              )}
            </p>
          </div>
        );

      case 4: // OpenEnded
        return (
          <div className="space-y-4">
            <div className="space-y-2">
              {questionResponses
                .filter((r) => r.textResponse)
                .map((r, i) => (
                  <div key={i} className="p-3 bg-muted rounded-lg text-sm">
                    {r.textResponse}
                  </div>
                ))}
            </div>
            <p className="text-center text-sm text-muted-foreground">
              {t(
                `Total Responses: ${totalResponses}`,
                `إجمالي الإجابات: ${totalResponses}`
              )}
            </p>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="container mx-auto py-8 space-y-8">
      <div className="space-y-4">
        <h1 className="text-3xl font-bold">{poll.title}</h1>
        <p className="text-muted-foreground">{poll.description}</p>
        <div className="text-sm text-muted-foreground">
          <p>
            {t("Start Date", "تاريخ البدء")}: {format(new Date(poll.startDate), "PPp")}
          </p>
          <p>
            {t("End Date", "تاريخ الانتهاء")}: {format(new Date(poll.endDate), "PPp")}
          </p>
        </div>
      </div>

      <Separator />

      <div className="grid gap-6">
        {questions.map((question) => (
          <Card key={question.id}>
            <CardHeader>
              <CardTitle>{question.question}</CardTitle>
              <p className="text-sm text-muted-foreground mt-1">
                {question.questionAr}
              </p>
            </CardHeader>
            <CardContent>{renderQuestionResults(question)}</CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}