"use client";

import Link from "next/link";
import { ClipboardList, Hourglass, UserX } from "lucide-react";
import type { ReactNode } from "react";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { ResponsesOverTimeChart } from "@/components/features/analytics/ResponsesOverTimeChart";
import { TrafficSourceChart } from "@/components/features/analytics/TrafficSourceChart";
import { formatNumber } from "@/lib/utils/format";
import { CHART_COLORS } from "@/config/chart-theme";
import type { DashboardOverview } from "@/lib/queries/dashboard-queries";

interface WorkspaceDashboardProps {
  overview: DashboardOverview;
}

export function WorkspaceDashboard({ overview }: WorkspaceDashboardProps) {
  const maxTop = Math.max(...overview.topSurveys.map((s) => s.responseCount), 1);

  return (
    <div className="space-y-5">
      <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 — last 14 days
          </h4>
          <p className="mb-3 text-[12px] text-muted">
            Completed responses across all surveys
          </p>
          <ResponsesOverTimeChart data={overview.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">Surveys by status</h4>
          <p className="mb-3 text-[12px] text-muted">
            {overview.surveyTotal} survey{overview.surveyTotal === 1 ? "" : "s"} in this workspace
          </p>
          <TrafficSourceChart
            data={overview.statusBreakdown}
            emptyLabel="No surveys yet."
            colors={overview.statusBreakdown.map((row) =>
              row.name === "Active"
                ? "#16A34A"
                : row.name === "Closed"
                  ? "#DC2626"
                  : "#64748B"
            )}
          />
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-3">
        <MiniCount
          icon={<ClipboardList className="h-4 w-4" />}
          label="Total surveys"
          value={overview.surveyTotal}
          hint={`${overview.surveyActive} live`}
          tint="bg-primary/10 text-primary"
        />
        <MiniCount
          icon={<Hourglass className="h-4 w-4" />}
          label="In progress"
          value={overview.inProgress}
          hint="Started, not finished"
          tint="bg-warning-bg text-warning"
        />
        <MiniCount
          icon={<UserX className="h-4 w-4" />}
          label="Abandoned"
          value={overview.abandoned}
          hint="Left without submitting"
          tint="bg-danger-bg text-danger"
        />
      </div>

      <div className="grid gap-4 lg:grid-cols-2">
        <div className="rounded-xl border border-border bg-card p-4 shadow sm:p-5">
          <div className="mb-4 flex items-center justify-between">
            <h4 className="text-sm font-bold text-navy">Top surveys</h4>
            <Link
              href="/app/surveys"
              className="text-xs font-semibold text-primary hover:underline"
            >
              View all
            </Link>
          </div>
          {overview.topSurveys.length === 0 ? (
            <p className="py-8 text-center text-sm text-muted">
              No surveys yet. Create one to see rankings here.
            </p>
          ) : (
            <div className="space-y-3">
              {overview.topSurveys.map((survey) => (
                <Link
                  key={survey.id}
                  href={`/app/surveys/${survey.id}/results`}
                  className="block rounded-lg p-1.5 transition-colors hover:bg-bg"
                >
                  <div className="mb-1 flex items-center justify-between gap-3 text-[13px]">
                    <span className="truncate font-semibold text-navy">
                      {survey.title}
                    </span>
                    <span className="shrink-0 font-mono text-xs font-bold text-muted">
                      {formatNumber(survey.responseCount)}
                    </span>
                  </div>
                  <div className="h-2 overflow-hidden rounded-full bg-[#F1F5F9]">
                    <div
                      className="h-full rounded-full"
                      style={{
                        width: `${(survey.responseCount / maxTop) * 100}%`,
                        backgroundColor: CHART_COLORS.primary,
                      }}
                    />
                  </div>
                </Link>
              ))}
            </div>
          )}
        </div>

        <div className="rounded-xl border border-border bg-card p-4 shadow sm:p-5">
          <div className="mb-4 flex items-center justify-between">
            <h4 className="text-sm font-bold text-navy">Active surveys</h4>
            <Link
              href="/app/surveys?status=active"
              className="text-xs font-semibold text-primary hover:underline"
            >
              Manage
            </Link>
          </div>
          {overview.activeSurveys.length === 0 ? (
            <p className="py-8 text-center text-sm text-muted">
              No live surveys. Publish a draft to start collecting answers.
            </p>
          ) : (
            <ul className="divide-y divide-border">
              {overview.activeSurveys.map((survey) => (
                <li
                  key={survey.id}
                  className="flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0"
                >
                  <div className="min-w-0">
                    <div className="truncate text-[13px] font-semibold text-navy">
                      {survey.title}
                    </div>
                    <div className="mt-0.5 flex items-center gap-2">
                      <Badge status="active" />
                      <span className="font-mono text-[11px] text-muted">
                        {formatNumber(survey.responseCount)} responses
                      </span>
                    </div>
                  </div>
                  <div className="flex shrink-0 gap-1.5">
                    <Link href={`/app/surveys/${survey.id}/results`}>
                      <Button variant="outline" size="sm" type="button">
                        Results
                      </Button>
                    </Link>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>

      <div className="rounded-xl border border-border bg-card p-4 shadow sm:p-5">
        <div className="mb-3 flex items-center justify-between">
          <h4 className="text-sm font-bold text-navy">Response quota</h4>
          <Link
            href="/app/billing"
            className="text-xs font-semibold text-primary hover:underline"
          >
            Upgrade
          </Link>
        </div>
        <div className="mb-2 flex items-baseline justify-between text-[13px]">
          <span className="font-medium text-muted capitalize">
            {overview.planTier} plan
          </span>
          <span className="font-mono text-sm font-bold text-navy">
            {formatNumber(overview.responseQuotaUsed)} /{" "}
            {formatNumber(overview.responseQuotaLimit)}
          </span>
        </div>
        <div className="h-2.5 overflow-hidden rounded-full bg-[#F1F5F9]">
          <div
            className="h-full rounded-full bg-gradient-to-r from-primary to-accent"
            style={{ width: `${overview.quotaPercent}%` }}
          />
        </div>
        <p className="mt-2 text-[12px] text-muted">
          {Math.max(0, overview.responseQuotaLimit - overview.responseQuotaUsed).toLocaleString()}{" "}
          responses remaining this cycle
        </p>
      </div>
    </div>
  );
}

function MiniCount({
  icon,
  label,
  value,
  hint,
  tint,
}: {
  icon: ReactNode;
  label: string;
  value: number;
  hint: string;
  tint: string;
}) {
  return (
    <div className="rounded-xl border border-border bg-card p-4 shadow">
      <div className="mb-3 flex items-center justify-between">
        <span className="text-xs font-semibold text-muted">{label}</span>
        <span
          className={`flex h-8 w-8 items-center justify-center rounded-md ${tint}`}
        >
          {icon}
        </span>
      </div>
      <div className="font-mono text-[26px] font-extrabold tracking-tight text-navy">
        {formatNumber(value)}
      </div>
      <p className="mt-1 text-[12px] text-muted">{hint}</p>
    </div>
  );
}
