import { useEffect, useState } from "react";
import { ArrowUpRight, AlertTriangle, PackageCheck, Truck } from "lucide-react";
import { Link } from "react-router-dom";

import { useAuth } from "@/auth/AuthProvider";
import {
  fetchFulfillmentOverview,
  type FulfillmentOverviewResponse,
} from "@/api/fulfillment";
import { Card } from "@/components/ui/card";

const statIcons = {
  "Open tasks": PackageCheck,
  Blocked: AlertTriangle,
  "Outbound ready": Truck,
} as const;

function timelineToneClassName(tone: string) {
  if (tone === "success") {
    return "bg-[#dff3ec] text-[var(--in-accent)]";
  }
  if (tone === "warning") {
    return "bg-[#fff0d8] text-[#b56a1f]";
  }

  return "bg-[#e9f4ff] text-[#245f92]";
}

export function DashboardPage() {
  const { token } = useAuth();
  const [overview, setOverview] = useState<FulfillmentOverviewResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!token?.access_token) {
      return;
    }

    let cancelled = false;

    setLoading(true);
    setError(null);

    fetchFulfillmentOverview(token.access_token)
      .then((response) => {
        if (!cancelled) {
          setOverview(response);
        }
      })
      .catch((nextError: Error) => {
        if (!cancelled) {
          setError(nextError.message);
          setOverview(null);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [token?.access_token]);

  return (
    <div className="grid gap-6 xl:grid-cols-[1fr_320px]">
      <div className="space-y-6">
        <section className="rounded-[32px] bg-[linear-gradient(135deg,#fff7e8_0%,#f4efe6_45%,#e2f3ec_100%)] px-6 py-7">
          <p className="text-sm font-semibold uppercase tracking-[0.18em] text-[var(--in-accent)]">Daily relay</p>
          <div className="mt-3 flex flex-wrap items-end justify-between gap-4">
            <div className="max-w-2xl">
              <h1 className="text-4xl font-black tracking-[-0.04em] text-[var(--in-text)]">주문 이행 상태와 예외 대응을 한 화면에서 이어붙이는 모바일 셸</h1>
              <p className="mt-4 text-base leading-7 text-[var(--in-muted)]">
                픽킹, 패킹, 예외 검토, 출고 준비까지 현재 이행 상태를 한눈에 보여주는 운영 모바일 surface다.
              </p>
            </div>
            <div className="rounded-[28px] border border-white/70 bg-white/80 px-5 py-4 shadow-sm">
              <p className="text-sm text-[var(--in-muted)]">Units in motion</p>
              <p className="mt-2 text-3xl font-black text-[var(--in-accent)]">{loading && !overview ? "..." : `${overview?.throughput_total ?? "0"} units`}</p>
            </div>
          </div>
          {error ? <p className="mt-4 text-sm font-semibold text-[#9d4d26]">{error}</p> : null}
        </section>

        <section className="grid gap-4 md:grid-cols-3">
          {(overview?.stats ?? []).map((stat) => {
            const Icon = statIcons[stat.label as keyof typeof statIcons] ?? PackageCheck;
            return (
              <Card key={stat.label} className="p-5 shadow-[0_18px_48px_rgba(25,54,46,0.06)]">
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <p className="text-sm text-[var(--in-muted)]">{stat.label}</p>
                    <p className="mt-3 text-3xl font-black text-[var(--in-text)]">{stat.value}</p>
                  </div>
                  <div className="rounded-2xl bg-[var(--in-accent-soft)] p-3 text-[var(--in-accent)]">
                    <Icon className="h-5 w-5" />
                  </div>
                </div>
              </Card>
            );
          })}
          {loading && !overview ? (
            <Card className="p-5 shadow-[0_18px_48px_rgba(25,54,46,0.06)] md:col-span-3">
              <p className="text-sm text-[var(--in-muted)]">Overview</p>
              <p className="mt-3 text-lg font-semibold text-[var(--in-text)]">서비스 현황을 불러오는 중입니다.</p>
            </Card>
          ) : null}
        </section>

        <Card className="p-6 shadow-[0_18px_48px_rgba(25,54,46,0.06)]">
          <div className="flex items-center justify-between gap-3">
            <div>
              <h2 className="text-xl font-black text-[var(--in-text)]">Relay timeline</h2>
              <p className="mt-2 text-sm text-[var(--in-muted)]">이행 단계별 handoff와 예외 대응 이벤트를 시간축으로 배치한다.</p>
            </div>
            <div className="flex items-center gap-2">
              <Link
                className="inline-flex items-center gap-2 rounded-full bg-[var(--in-accent-soft)] px-3 py-2 text-sm font-semibold text-[var(--in-accent)]"
                to="/shipping"
              >
                Shipping
                <ArrowUpRight className="h-4 w-4" />
              </Link>
              <Link
                className="inline-flex items-center gap-2 rounded-full bg-[var(--in-accent-soft)] px-3 py-2 text-sm font-semibold text-[var(--in-accent)]"
                to="/fulfillment"
              >
                Fulfillment
                <ArrowUpRight className="h-4 w-4" />
              </Link>
            </div>
          </div>

          <div className="mt-6 grid gap-4 md:grid-cols-3">
            {loading && !(overview?.timeline.length ?? 0) ? <div className="text-sm text-[var(--in-muted)] md:col-span-3">타임라인을 불러오는 중입니다.</div> : null}
            {!loading && !error && !(overview?.timeline.length ?? 0) ? (
              <div className="text-sm text-[var(--in-muted)] md:col-span-3">표시할 타임라인 이벤트가 없습니다.</div>
            ) : null}
            {(overview?.timeline ?? []).map((item) => (
              <div key={item.time} className="rounded-[24px] border border-[var(--in-border)] bg-white p-5">
                <div className={`inline-flex rounded-full px-3 py-1 text-xs font-semibold ${timelineToneClassName(item.tone)}`}>{item.time}</div>
                <p className="mt-4 text-lg font-bold text-[var(--in-text)]">{item.title}</p>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <Card className="p-6 shadow-[0_18px_48px_rgba(25,54,46,0.06)]">
        <h2 className="text-xl font-black text-[var(--in-text)]">Stage load</h2>
        <p className="mt-2 text-sm text-[var(--in-muted)]">현재 진행 중인 단계별 작업량과 병목 구간을 우선순위 큐로 보여준다.</p>

        <div className="mt-6 space-y-4">
          {loading && !(overview?.stage_load.length ?? 0) ? <div className="text-sm text-[var(--in-muted)]">단계별 적재량을 불러오는 중입니다.</div> : null}
          {!loading && !error && !(overview?.stage_load.length ?? 0) ? <div className="text-sm text-[var(--in-muted)]">표시할 단계 데이터가 없습니다.</div> : null}
          {(overview?.stage_load ?? []).map((entry) => (
            <div key={entry.label}>
              <div className="flex items-center justify-between text-sm">
                <span className="font-semibold text-[var(--in-text)]">{entry.label}</span>
                <span className="text-[var(--in-muted)]">{entry.value}</span>
              </div>
            </div>
          ))}
          {error ? <div className="text-sm font-semibold text-[#9d4d26]">{error}</div> : null}
        </div>
      </Card>
    </div>
  );
}
