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 className={`h-full ${CARD_STYLES.subtle} shadow-none`}>
    <DashboardSectionHeader title={title} compact accent={false} />
    <CardContent className="p-0">
      <ScrollArea className="h-[400px]">
        <div className="divide-y divide-[#f5f3f0]">
          {responses.items.map((response) => (
            <div key={response.token} className="p-3 transition-colors hover:bg-[#faf9f7]">
              {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-[13px] font-semibold text-[#2b2925] hover:underline"
                >
                  {response.hidden?.name || "Anonymous"}
                </a>
              ) : (
                <span className="text-[13px] font-semibold text-[#2b2925]">
                  {response.hidden?.name || "Anonymous"}
                </span>
              )}
              <DashboardBadge variant={answer?.boolean ? "success" : "error"}>
                {answer?.boolean ? "Yes" : "No"}
              </DashboardBadge>
            </div>
            <time
              className="text-[11px] text-[#a09b92]"
              dateTime={response.submitted_at}
            >
              {format(new Date(response.submitted_at), "MMM d")}
            </time>
          </div>
          {textAnswer && (
            <div className="text-[11.5px] text-[#7c7870]">"{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-[13px] font-semibold text-[#2b2925] hover:underline"
                >
                  {response.hidden?.name || "Anonymous"}
                </a>
              ) : (
                <span className="text-[13px] font-semibold text-[#2b2925]">
                  {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-[11px] text-[#a09b92]"
              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-[11.5px] text-[#7c7870]">
              {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"
        size="large"
      />
      <CardContent className="p-4 pt-3 space-y-3">
        {loading ? (
          <div className="space-y-3">
            <ChartSkeleton height="md" withCard={false} />
            <TableSkeleton rows={5} columns={3} />
          </div>
        ) : (
          <>
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
              <Card className="rounded-[12px] border-[#efede9] shadow-none">
                <CardHeader className="p-4 pb-3">
                  <div className="flex items-baseline justify-between gap-2">
                    <CardTitle className="text-[12.5px] font-semibold tracking-tight text-[#2b2925]">
                      How likely are you to place another order with us?
                    </CardTitle>
                    <span
                      className={`text-lg font-bold tabular-nums ${
                        metrics.winback.averageRating <= 1
                          ? "text-[#b3503f]"
                          : metrics.winback.averageRating <= 2
                          ? "text-[#c9973d]"
                          : metrics.winback.averageRating <= 3
                          ? "text-[#b39b2e]"
                          : metrics.winback.averageRating <= 4
                          ? "text-[#7fa653]"
                          : "text-[#2e8f5b]"
                      }`}
                    >
                      {metrics.winback.averageRating}
                      <span className="text-xs font-normal text-muted-foreground">
                        /5 avg
                      </span>
                    </span>
                  </div>
                </CardHeader>
                <CardContent className="p-4 pt-0">
                  <div className="h-[132px]">
                    <ResponsiveContainer width="100%" height="100%">
                      <BarChart
                        data={likelihoodCounts}
                        margin={{ top: 4, right: 0, left: 0, bottom: -25 }}
                      >
                        <CartesianGrid strokeDasharray="3 4" stroke="#efede9" vertical={false} />
                        <XAxis
                          dataKey="rating"
                          tickFormatter={(value) => {
                            return value === "1"
                              ? "Not at all"
                              : value === "5"
                              ? "Extremely"
                              : "";
                          }}
                          textAnchor="middle"
                          interval={0}
                          height={50}
                          tick={{ fill: "#a09b92", fontSize: 11 }}
                          tickLine={false}
                          axisLine={{ stroke: "#eceae5" }}
                        />
                        <YAxis
                          width={36}
                          tick={{ fill: "#a09b92", fontSize: 11 }}
                          tickLine={false}
                          axisLine={false}
                        />
                        <Tooltip
                          content={
                            <SimpleTooltip
                              labelFormatter={(label) => `${label} Rating`}
                              valueFormatter={(value) => `${value} responses`}
                            />
                          }
                        />
                        <Bar dataKey="count" radius={[6, 6, 0, 0]}>
                          {likelihoodCounts.map((_, index) => (
                            <Cell
                              key={`cell-${index}`}
                              fill={
                                index === 0
                                  ? "#b3503f" // red
                                  : index === 1
                                  ? "#c9973d" // orange
                                  : index === 2
                                  ? "#d4b445" // yellow
                                  : index === 3
                                  ? "#7fa653" // lime
                                  : "#2e8f5b" // green
                              }
                            />
                          ))}
                        </Bar>
                      </BarChart>
                    </ResponsiveContainer>
                  </div>
                </CardContent>
              </Card>
              <Card className="rounded-[12px] border-[#efede9] shadow-none">
                <CardHeader className="p-4 pb-3">
                  <CardTitle className="text-[12.5px] font-semibold tracking-tight text-[#2b2925]">
                    Were the suggested products in this email relevant to you?
                  </CardTitle>
                </CardHeader>
                <CardContent className="p-4 pt-0">
                  {/* CSS proportion bar — guarantees matching rounded ends on
                      both segments (recharts stacked-bar radius rounds unreliably) */}
                  {(() => {
                    const yes = metrics.productRelevance.yesCount;
                    const no = metrics.productRelevance.noCount;
                    const total = yes + no || 1;
                    const yesPct = Math.round((yes / total) * 100);
                    return (
                      <div className="flex h-[52px] w-full gap-1 overflow-hidden rounded-xl">
                        <div
                          className="flex items-center justify-center rounded-l-xl bg-[#2e8f5b] text-sm font-bold text-white"
                          style={{ width: `${(yes / total) * 100}%` }}
                          title={`Yes: ${yes.toLocaleString()} (${yesPct}%)`}
                        >
                          {yesPct >= 12 && `${yesPct}%`}
                        </div>
                        <div
                          className="flex items-center justify-center rounded-r-xl bg-[#b3503f] text-sm font-bold text-white"
                          style={{ width: `${(no / total) * 100}%` }}
                          title={`No: ${no.toLocaleString()} (${100 - yesPct}%)`}
                        >
                          {100 - yesPct >= 12 && `${100 - yesPct}%`}
                        </div>
                      </div>
                    );
                  })()}
                  <div className="mt-2 flex justify-between px-1 text-xs font-medium text-[#7c7870]">
                    <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-3">
              <div className="col-span-4 lg:col-span-12 xl:col-span-4">
                <Card className="rounded-[12px] border-[#efede9] shadow-none h-full">
                  <DashboardSectionHeader title="Reasons for Not Ordering" compact accent={false} />
                  <CardContent className="p-4 pt-3">
                    <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;
