"use client";

import { Suspense } from "react";
import { Eye, MessageSquare, Percent, Timer } from "lucide-react";
import { StatCard } from "@/components/shared/StatCard";
import { formatCount, formatPercent } from "@/lib/utils/analytics-format";
import type { SurveyAnalytics } from "@/types/analytics";
import { AnalyticsFilterBar } from "./AnalyticsFilterBar";
import { ResponsesOverTimeChart } from "./ResponsesOverTimeChart";
import { TrafficSourceChart } from "./TrafficSourceChart";
import { QuestionResultCard } from "./QuestionResultCard";
import { RespondentsTable } from "./RespondentsTable";

interface AnalyticsDashboardProps {
  analytics: SurveyAnalytics;
  exportQuery: string;
}

export function AnalyticsDashboard({
  analytics,
  exportQuery,
}: AnalyticsDashboardProps) {
  const { overview } = analytics;

  return (
    <div className="space-y-5 sm:space-y-6">
      <Suspense fallback={null}>
        <AnalyticsFilterBar />
      </Suspense>

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 sm:gap-4">
        <StatCard
          label="Total Views"
          value={formatCount(overview.totalViews)}
          icon={<Eye className="h-4 w-4 text-primary" />}
          iconClassName="bg-primary/10"
        />
        <StatCard
          label="Responses"
          value={formatCount(overview.responses)}
          icon={<MessageSquare className="h-4 w-4 text-accent" />}
          iconClassName="bg-accent/10"
        />
        <StatCard
          label="Completion Rate"
          value={formatPercent(overview.completionRate)}
          icon={<Percent className="h-4 w-4 text-success" />}
          iconClassName="bg-success/10"
        />
        <StatCard
          label="Avg. Time"
          value={overview.avgTimeToComplete}
          icon={<Timer className="h-4 w-4 text-navy" />}
          iconClassName="bg-navy/10"
        />
      </div>

      <div className="grid gap-4 lg:grid-cols-[1.4fr_1fr]">
        <div className="rounded-xl border border-border bg-card p-4 shadow sm:p-5">
          <h4 className="mb-1 text-sm font-bold text-navy">Responses over time</h4>
          <p className="mb-3 text-[12px] text-muted">
            Completed surveys by day
          </p>
          <ResponsesOverTimeChart data={analytics.responsesOverTime} />
        </div>
        <div className="rounded-xl border border-border bg-card p-4 shadow sm:p-5">
          <h4 className="mb-1 text-sm font-bold text-navy">Traffic source</h4>
          <p className="mb-3 text-[12px] text-muted">
            Where respondents came from
          </p>
          <TrafficSourceChart data={analytics.trafficSources} />
        </div>
      </div>

      {analytics.questions.length > 0 ? (
        <div className="space-y-4">
          <h3 className="text-sm font-bold text-navy">Question breakdown</h3>
          {analytics.questions.map((q, i) => (
            <QuestionResultCard key={q.questionId} question={q} index={i} />
          ))}
        </div>
      ) : (
        <div className="rounded-lg border border-border bg-card p-8 text-center shadow">
          <p className="text-sm text-muted">
            Add questions to your survey to see per-question breakdowns.
          </p>
        </div>
      )}

      <div className="rounded-lg border border-border bg-card shadow">
        <div className="flex items-center justify-between border-b border-border px-4 py-3 sm:px-5">
          <h4 className="text-sm font-bold text-navy">Individual responses</h4>
          <a
            href={`/api/surveys/${analytics.surveyId}/export/csv?${exportQuery}`}
            className="text-xs font-semibold text-primary hover:underline"
          >
            Download all (CSV)
          </a>
        </div>
        <RespondentsTable
          surveyId={analytics.surveyId}
          respondents={analytics.respondents.map((r) => ({
            ...r,
            startedAt: new Date(r.startedAt),
            completedAt: r.completedAt ? new Date(r.completedAt) : null,
          }))}
        />
      </div>
    </div>
  );
}
