import React, { useState, useEffect } from "react";
import { apiClient } from "@/utils/apiClient";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { ScrollArea } from "@/components/ui/scroll-area";
import { format } from "date-fns";
import { CARD_STYLES } from "@/lib/dashboard/designTokens";
import {
  DashboardSectionHeader,
  DashboardErrorState,
  DashboardBadge,
  DashboardTable,
  ChartSkeleton,
  TableSkeleton,
  SimpleTooltip,
  TOOLTIP_STYLES,
} from "@/components/dashboard/shared";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Cell,
} from "recharts";

// Get form IDs from environment variables
const FORM_IDS = {
  FORM_1: import.meta.env.VITE_TYPEFORM_FORM_ID_1,
  FORM_2: import.meta.env.VITE_TYPEFORM_FORM_ID_2,
};

const FORM_NAMES = {
  [FORM_IDS.FORM_1]: "Product Relevance",
  [FORM_IDS.FORM_2]: "Winback Survey",
};

const ResponseFeed = ({ responses, title, renderSummary }) => (
  <Card>
    <DashboardSectionHeader title={title} compact />
    <CardContent>
      <ScrollArea className="h-[400px]">
        <div className="divide-y divide-border/50">
          {responses.items.map((response) => (
            <div key={response.token} className="p-4">
              {renderSummary(response)}
            </div>
          ))}
        </div>
      </ScrollArea>
    </CardContent>
  </Card>
);

const ProductRelevanceFeed = ({ responses }) => (
  <ResponseFeed
    responses={responses}
    title="Product Relevance Responses"
    renderSummary={(response) => {
      const answer = response.answers?.find((a) => a.type === "boolean");
      const textAnswer = response.answers?.find((a) => a.type === "text")?.text;

      return (
        <div className="space-y-1.5">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              {response.hidden?.email ? (
                <a
                  href={`https://backend.acherryontop.com/search/?search_for=customers&search=${response.hidden.email}`}
                  className="text-sm font-medium text-foreground hover:underline"
                >
                  {response.hidden?.name || "Anonymous"}
                </a>
              ) : (
                <span className="text-sm font-medium text-foreground">
                  {response.hidden?.name || "Anonymous"}
                </span>
              )}
              <DashboardBadge variant={answer?.boolean ? "success" : "error"}>
                {answer?.boolean ? "Yes" : "No"}
              </DashboardBadge>
            </div>
            <time
              className="text-xs text-muted-foreground"
              dateTime={response.submitted_at}
            >
              {format(new Date(response.submitted_at), "MMM d")}
            </time>
          </div>
          {textAnswer && (
            <div className="text-sm text-muted-foreground">"{textAnswer}"</div>
          )}
        </div>
      );
    }}
  />
);

const WinbackFeed = ({ responses }) => (
  <ResponseFeed
    responses={responses}
    title="Winback Survey Responses"
    renderSummary={(response) => {
      const likelihoodAnswer = response.answers?.find(
        (a) => a.type === "number"
      );
      const reasonsAnswer = response.answers?.find((a) => a.type === "choices");
      const feedbackAnswer = response.answers?.find(
        (a) => a.type === "text" && a.field.type === "long_text"
      );

      return (
        <div className="space-y-1.5">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              {response.hidden?.email ? (
                <a
                  href={`https://backend.acherryontop.com/search/?search_for=customers&search=${response.hidden.email}`}
                  className="text-sm font-medium text-foreground hover:underline"
                >
                  {response.hidden?.name || "Anonymous"}
                </a>
              ) : (
                <span className="text-sm font-medium text-foreground">
                  {response.hidden?.name || "Anonymous"}
                </span>
              )}
              <DashboardBadge
                variant={
                  likelihoodAnswer?.number === 1
                    ? "error"
                    : likelihoodAnswer?.number === 2
                    ? "orange"
                    : likelihoodAnswer?.number === 3
                    ? "yellow"
                    : likelihoodAnswer?.number === 4
                    ? "emerald"
                    : likelihoodAnswer?.number === 5
                    ? "success"
                    : "default"
                }
              >
                {likelihoodAnswer?.number}/5
              </DashboardBadge>
            </div>
            <time
              className="text-xs text-muted-foreground"
              dateTime={response.submitted_at}
            >
              {format(new Date(response.submitted_at), "MMM d")}
            </time>
          </div>
          <div className="flex flex-wrap gap-1">
            {(reasonsAnswer?.choices?.labels || []).map((label, idx) => (
              <DashboardBadge key={idx} variant="default" size="sm">
                {label}
              </DashboardBadge>
            ))}
            {reasonsAnswer?.choices?.other && (
              <DashboardBadge variant="purple" size="sm">
                {reasonsAnswer.choices.other}
              </DashboardBadge>
            )}
          </div>
          {feedbackAnswer?.text && (
            <div className="text-sm text-muted-foreground">
              {feedbackAnswer.text}
            </div>
          )}
        </div>
      );
    }}
  />
);

const TypeformDashboard = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [formData, setFormData] = useState({
    form1: { responses: null, hasMore: false, lastToken: null },
    form2: { responses: null, hasMore: false, lastToken: null },
  });

  const fetchResponses = async (formId, before = null) => {
    const params = { page_size: 1000 };
    if (before) params.before = before;

    const response = await apiClient.get(
      `/api/typeform/forms/${formId}/responses`,
      { params }
    );
    return response.data;
  };

  useEffect(() => {
    const fetchFormData = async () => {
      try {
        setLoading(true);
        setError(null);

        const forms = [FORM_IDS.FORM_1, FORM_IDS.FORM_2];
        const results = await Promise.all(
          forms.map(async (formId) => {
            const responses = await fetchResponses(formId);
            const hasMore = responses.items.length === 1000;
            const lastToken = hasMore
              ? responses.items[responses.items.length - 1].token
              : null;

            return {
              responses,
              hasMore,
              lastToken,
            };
          })
        );

        setFormData({
          form1: results[0],
          form2: results[1],
        });
      } catch (err) {
        console.error("Error fetching Typeform data:", err);
        setError("Failed to load form data. Please try again later.");
      } finally {
        setLoading(false);
      }
    };

    fetchFormData();
  }, []);

  const calculateMetrics = () => {
    if (!formData.form1.responses || !formData.form2.responses) return null;

    const form1Responses = formData.form1.responses.items;
    const form2Responses = formData.form2.responses.items;

    // Product Relevance metrics
    const yesResponses = form1Responses.filter((r) =>
      r.answers?.some((a) => a.type === "boolean" && a.boolean === true)
    ).length;
    const totalForm1 = form1Responses.length;
    const yesPercentage = Math.round((yesResponses / totalForm1) * 100) || 0;

    // Winback Survey metrics
    const likelihoodAnswers = form2Responses
      .map((r) => r.answers?.find((a) => a.type === "number"))
      .filter(Boolean)
      .map((a) => a.number);
    const averageLikelihood = likelihoodAnswers.length
      ? Math.round(
          (likelihoodAnswers.reduce((a, b) => a + b, 0) /
            likelihoodAnswers.length) *
            10
        ) / 10
      : 0;

    // Get reasons for not ordering (only predefined choices)
    const reasonsMap = new Map();
    form2Responses.forEach((response) => {
      const reasonsAnswer = response.answers?.find((a) => a.type === "choices");
      if (reasonsAnswer?.choices?.labels) {
        reasonsAnswer.choices.labels.forEach((label) => {
          reasonsMap.set(label, (reasonsMap.get(label) || 0) + 1);
        });
      }
    });

    const sortedReasons = Array.from(reasonsMap.entries())
      .sort(([, a], [, b]) => b - a)
      .map(([label, count]) => ({
        reason: label,
        count,
        percentage: Math.round((count / form2Responses.length) * 100),
      }));

    return {
      productRelevance: {
        yesPercentage,
        yesCount: yesResponses,
        noCount: totalForm1 - yesResponses,
      },
      winback: {
        averageRating: averageLikelihood,
        reasons: sortedReasons,
      },
    };
  };

  const metrics = loading ? null : calculateMetrics();

  // Find the newest response across both forms
  const getNewestResponse = () => {
    if (
      !formData.form1.responses?.items?.length &&
      !formData.form2.responses?.items?.length
    )
      return null;

    const form1Latest = formData.form1.responses?.items[0]?.submitted_at;
    const form2Latest = formData.form2.responses?.items[0]?.submitted_at;

    if (!form1Latest) return form2Latest;
    if (!form2Latest) return form1Latest;

    return new Date(form1Latest) > new Date(form2Latest)
      ? form1Latest
      : form2Latest;
  };

  const newestResponse = getNewestResponse();

  // Column definitions for reasons table
  const reasonsColumns = [
    {
      key: "reason",
      header: "Reason",
      render: (value) => <span className="font-medium text-foreground">{value}</span>,
    },
    {
      key: "count",
      header: "Count",
      align: "right",
      render: (value) => <span className="text-muted-foreground">{value}</span>,
    },
    {
      key: "percentage",
      header: "%",
      align: "right",
      width: "w-[80px]",
      render: (value) => <span className="text-muted-foreground">{value}%</span>,
    },
  ];

  if (error) {
    return (
      <Card className={`h-full ${CARD_STYLES.base}`}>
        <CardContent className="p-4">
          <DashboardErrorState
            title="Failed to load survey data"
            message={error}
          />
        </CardContent>
      </Card>
    );
  }

  // Calculate likelihood counts for the chart
  const likelihoodCounts =
    !loading && formData.form2.responses
      ? [1, 2, 3, 4, 5].map((rating) => ({
          rating: rating.toString(),
          count: formData.form2.responses.items.filter(
            (r) =>
              r.answers?.find((a) => a.type === "number")?.number === rating
          ).length,
        }))
      : [];

  return (
    <Card className={CARD_STYLES.base}>
      <DashboardSectionHeader
        title="Customer Surveys"
        lastUpdated={newestResponse ? new Date(newestResponse) : null}
        lastUpdatedFormat={(date) => `Newest response: ${format(date, "MMM d, h:mm a")}`}
        className="pb-0"
      />
      <CardContent className="space-y-4">
        {loading ? (
          <div className="space-y-4">
            <ChartSkeleton height="md" withCard={false} />
            <TableSkeleton rows={5} columns={3} />
          </div>
        ) : (
          <>
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-6">
              <Card className="bg-card">
                <CardHeader className="p-6">
                  <div className="flex items-baseline justify-between">
                    <CardTitle className="text-lg font-semibold">
                      How likely are you to place another order with us?
                    </CardTitle>
                    <span
                      className={`text-2xl font-bold ${
                        metrics.winback.averageRating <= 1
                          ? "text-red-600 dark:text-red-500"
                          : metrics.winback.averageRating <= 2
                          ? "text-orange-600 dark:text-orange-500"
                          : metrics.winback.averageRating <= 3
                          ? "text-yellow-600 dark:text-yellow-500"
                          : metrics.winback.averageRating <= 4
                          ? "text-lime-600 dark:text-lime-500"
                          : "text-green-600 dark:text-green-500"
                      }`}
                    >
                      {metrics.winback.averageRating}
                      <span className="text-base font-normal text-muted-foreground">
                        /5 avg
                      </span>
                    </span>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="h-[200px]">
                    <ResponsiveContainer width="100%" height="100%">
                      <BarChart
                        data={likelihoodCounts}
                        margin={{ top: 0, right: 10, left: -20, bottom: -25 }}
                      >
                        <CartesianGrid
                          strokeDasharray="3 3"
                          className="stroke-muted"
                        />
                        <XAxis
                          dataKey="rating"
                          tickFormatter={(value) => {
                            return value === "1"
                              ? "Not at all"
                              : value === "5"
                              ? "Extremely"
                              : "";
                          }}
                          textAnchor="middle"
                          interval={0}
                          height={50}
                          className="text-muted-foreground text-xs md:text-sm"
                        />
                        <YAxis className="text-muted-foreground text-xs md:text-sm" />
                        <Tooltip
                          content={
                            <SimpleTooltip
                              labelFormatter={(label) => `${label} Rating`}
                              valueFormatter={(value) => `${value} responses`}
                            />
                          }
                        />
                        <Bar dataKey="count">
                          {likelihoodCounts.map((_, index) => (
                            <Cell
                              key={`cell-${index}`}
                              fill={
                                index === 0
                                  ? "#ef4444" // red
                                  : index === 1
                                  ? "#f97316" // orange
                                  : index === 2
                                  ? "#eab308" // yellow
                                  : index === 3
                                  ? "#84cc16" // lime
                                  : "#10b981" // green
                              }
                            />
                          ))}
                        </Bar>
                      </BarChart>
                    </ResponsiveContainer>
                  </div>
                </CardContent>
              </Card>
              <Card className="bg-card">
                <CardHeader className="p-6">
                  <div className="flex items-baseline justify-between gap-2">
                    <CardTitle className="text-lg font-semibold">
                      Were the suggested products in this email relevant to you?
                    </CardTitle>
                    <div className="flex flex-col items-end">
                      <span className="text-2xl font-bold text-green-600 dark:text-green-500">
                        {metrics.productRelevance.yesPercentage}% Relevant
                      </span>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="h-[100px]">
                    <ResponsiveContainer width="100%" height="100%">
                      <BarChart
                        data={[
                          {
                            yes: metrics.productRelevance.yesCount,
                            no: metrics.productRelevance.noCount,
                            total:
                              metrics.productRelevance.yesCount +
                              metrics.productRelevance.noCount,
                          },
                        ]}
                        layout="vertical"
                        stackOffset="expand"
                        margin={{ top: 0, right: 0, left: -20, bottom: 0 }}
                      >
                        <XAxis type="number" hide domain={[0, 1]} />
                        <YAxis type="category" hide />
                        <Tooltip
                          cursor={false}
                          content={({ payload }) => {
                            if (payload && payload.length) {
                              const yesCount = payload[0].payload.yes;
                              const noCount = payload[0].payload.no;
                              const total = yesCount + noCount;
                              const yesPercent = Math.round((yesCount / total) * 100);
                              const noPercent = Math.round((noCount / total) * 100);
                              return (
                                <div className={TOOLTIP_STYLES.container}>
                                  <div className={TOOLTIP_STYLES.content}>
                                    <div className={TOOLTIP_STYLES.row}>
                                      <div className={TOOLTIP_STYLES.rowLabel}>
                                        <span className={TOOLTIP_STYLES.dot} style={{ backgroundColor: '#10b981' }} />
                                        <span className={TOOLTIP_STYLES.name}>Yes</span>
                                      </div>
                                      <span className={TOOLTIP_STYLES.value}>{yesCount} ({yesPercent}%)</span>
                                    </div>
                                    <div className={TOOLTIP_STYLES.row}>
                                      <div className={TOOLTIP_STYLES.rowLabel}>
                                        <span className={TOOLTIP_STYLES.dot} style={{ backgroundColor: '#ef4444' }} />
                                        <span className={TOOLTIP_STYLES.name}>No</span>
                                      </div>
                                      <span className={TOOLTIP_STYLES.value}>{noCount} ({noPercent}%)</span>
                                    </div>
                                  </div>
                                </div>
                              );
                            }
                            return null;
                          }}
                        />
                        <Bar
                          dataKey="yes"
                          stackId="stack"
                          fill="#10b981"
                          radius={[0, 0, 0, 0]}
                        >
                          <text
                            x="50%"
                            y="50%"
                            textAnchor="middle"
                            fill="#fff"
                            fontSize={14}
                            fontWeight="bold"
                          >
                            {metrics.productRelevance.yesPercentage}%
                          </text>
                        </Bar>
                        <Bar
                          dataKey="no"
                          stackId="stack"
                          fill="#ef4444"
                          radius={[0, 0, 0, 0]}
                        />
                      </BarChart>
                    </ResponsiveContainer>
                  </div>
                  <div className="flex justify-between mt-2 text-md font-semibold mx-1 text-muted-foreground">
                    <div>Yes: {metrics.productRelevance.yesCount}</div>
                    <div>No: {metrics.productRelevance.noCount}</div>
                  </div>
                </CardContent>
              </Card>
            </div>

            <div className="grid grid-cols-2 lg:grid-cols-12 gap-4">
              <div className="col-span-4 lg:col-span-12 xl:col-span-4">
                <Card className="bg-card h-full">
                  <DashboardSectionHeader title="Reasons for Not Ordering" compact />
                  <CardContent>
                    <DashboardTable
                      columns={reasonsColumns}
                      data={metrics?.winback?.reasons || []}
                      getRowKey={(reason, index) => `${reason.reason}-${index}`}
                      maxHeight="md"
                      compact
                    />
                  </CardContent>
                </Card>
              </div>

              <div className="col-span-4 lg:col-span-6 xl:col-span-4">
                <WinbackFeed responses={formData.form2.responses} />
              </div>
              <div className="col-span-4 lg:col-span-6 xl:col-span-4">
                <ProductRelevanceFeed responses={formData.form1.responses} />
              </div>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
};

export default TypeformDashboard;
