"use client";

import { useState } from "react";
import useSWR from "swr";
import {
  BarChart3,
  CalendarClock,
  CloudDownload,
  Crown,
  Target,
} from "lucide-react";
import { toast } from "sonner";
import type { SdgsDesa } from "@/lib/types";
import { ApiError, apiSend, fetcher } from "@/lib/api";
import { StatCard } from "@/components/page-header";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";

export function SdgsPanel({ isAdmin }: { isAdmin: boolean }) {
  const { data, isLoading, mutate } = useSWR<SdgsDesa | null>("/sdgs", fetcher);
  const [syncing, setSyncing] = useState(false);

  const skor = data?.skor ?? [];
  const tertinggi = skor.reduce<SdgsDesa["skor"][number] | null>(
    (best, item) => (!best || item.skor > best.skor ? item : best),
    null,
  );
  const terendah = skor.reduce<SdgsDesa["skor"][number] | null>(
    (low, item) => (!low || item.skor < low.skor ? item : low),
    null,
  );
  const capaian = skor.filter((item) => item.skor >= 70).length;
  const diperbarui = data?.updatedAt
    ? new Date(data.updatedAt).toLocaleDateString("id-ID", {
        day: "numeric",
        month: "long",
        year: "numeric",
      })
    : "-";

  async function sync() {
    setSyncing(true);
    try {
      await apiSend<SdgsDesa>("/sdgs/sync", "POST");
      toast.success("Skor SDGs diperbarui dari API Kemendesa");
      await mutate();
    } catch (error) {
      toast.error(
        error instanceof ApiError ? error.message : "Gagal sinkron skor SDGs",
      );
    } finally {
      setSyncing(false);
    }
  }

  if (isLoading) {
    return (
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {Array.from({ length: 4 }).map((_, index) => (
          <div key={index} className="h-24 animate-pulse rounded-xl bg-muted" />
        ))}
      </div>
    );
  }

  if (!data) {
    return (
      <Card>
        <CardContent className="py-16 text-center">
          <p className="font-semibold">Belum ada data SDGs</p>
          <p className="mt-1 text-sm text-muted-foreground">
            Klik Sinkron SDGs untuk mengambil skor 18 tujuan dari API
            Kemendesa.
          </p>
          {isAdmin && (
            <Button className="mt-4" onClick={sync} disabled={syncing}>
              <CloudDownload className="h-4 w-4" />
              {syncing ? "Menyinkronkan…" : "Sinkron SDGs"}
            </Button>
          )}
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      {isAdmin && (
        <div className="flex justify-end">
          <Button variant="outline" onClick={sync} disabled={syncing}>
            <CloudDownload className="h-4 w-4" />
            {syncing ? "Menyinkronkan…" : "Sinkron SDGs"}
          </Button>
        </div>
      )}

      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard
          title="Skor SDGs"
          value={data.rataRata.toFixed(2)}
          hint={`Snapshot ${data.tahun} · ${data.sumber ?? "Kemendesa"}`}
          icon={BarChart3}
        />
        <StatCard
          title="Tujuan terkuat"
          value={tertinggi ? tertinggi.skor.toFixed(2) : "-"}
          hint={tertinggi ? `Tujuan ${tertinggi.goals} · ${tertinggi.judul}` : undefined}
          icon={Crown}
          tone="amber"
        />
        <StatCard
          title="Perlu perhatian"
          value={terendah ? terendah.skor.toFixed(2) : "-"}
          hint={terendah ? `Tujuan ${terendah.goals} · ${terendah.judul}` : undefined}
          icon={Target}
          tone="sky"
        />
        <StatCard
          title="Tujuan ≥ 70"
          value={`${capaian}/18`}
          hint={`Diperbarui ${diperbarui}`}
          icon={CalendarClock}
          tone="violet"
        />
      </div>

      <Card>
        <CardContent className="space-y-4">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div>
              <h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
                Skor per tujuan
              </h2>
              <p className="mt-1 text-xs text-muted-foreground">
                Skala 0–100. Sinkronisasi mengambil data terbaru dari
                sid.kemendesa.go.id.
              </p>
            </div>
            <span className="rounded-full bg-primary/10 px-3 py-1 text-xs font-semibold text-primary">
              Rata-rata {data.rataRata.toFixed(2)}
            </span>
          </div>

          <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
            {data.skor.map((item) => {
              const lebar = Math.min(100, Math.max(0, item.skor));
              return (
                <div
                  key={item.id}
                  className="rounded-xl border border-border bg-card p-4 shadow-sm transition-shadow hover:shadow-md"
                >
                  <div className="flex items-start justify-between gap-3">
                    <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-brand-gradient text-xs font-bold text-primary-foreground">
                      {item.goals}
                    </div>
                    <span className="text-lg font-bold tracking-tight">
                      {item.skor.toFixed(2)}
                    </span>
                  </div>
                  <p className="mt-3 min-h-[2.5rem] text-sm font-semibold leading-snug">
                    {item.judul}
                  </p>
                  <div className="mt-3 h-1.5 overflow-hidden rounded-full bg-muted">
                    <div
                      className="h-full rounded-full bg-brand-gradient"
                      style={{ width: `${lebar}%` }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
