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

import {
  fetchShipments,
  fetchShippingOverview,
  updateShipmentStatus,
  type ShipmentSummary,
  type ShippingOverviewResponse,
} from "@/api/shipping";
import { useAuth } from "@/auth/AuthProvider";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";

function shippingStatusClassName(status: string) {
  if (status === "Delivered") {
    return "bg-[#dff3ec] text-[var(--in-accent)]";
  }
  if (status === "Delayed") {
    return "bg-[#ffe2d7] text-[#c4663a]";
  }
  if (status === "Out for delivery") {
    return "bg-[#e9f4ff] text-[#245f92]";
  }

  return "bg-[#fff0d8] text-[#b56a1f]";
}

function shippingActionPayload(status: string) {
  if (status === "Delayed") {
    return {
      label: "재개",
      body: {
        status: "In transit",
        last_event: "재배차 완료",
        eta: "2026.03.14 20:30",
      },
      variant: "secondary" as const,
    };
  }

  if (status === "Delivered") {
    return null;
  }

  return {
    label: "완료",
    body: {
      status: "Delivered",
      last_event: "고객 인수 완료",
      eta: "2026.03.14 19:10",
    },
    variant: "default" as const,
  };
}

export function ShippingPage() {
  const { token } = useAuth();
  const [overview, setOverview] = useState<ShippingOverviewResponse | null>(null);
  const [shipments, setShipments] = useState<ShipmentSummary[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [pendingShipmentId, setPendingShipmentId] = useState<string | null>(null);

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

    let cancelled = false;

    async function loadShippingData() {
      setLoading(true);
      setError(null);

      try {
        const [overviewResponse, shipmentResponse] = await Promise.all([
          fetchShippingOverview(currentAccessToken),
          fetchShipments(currentAccessToken),
        ]);
        if (!cancelled) {
          setOverview(overviewResponse);
          setShipments(shipmentResponse);
        }
      } catch (nextError) {
        if (!cancelled) {
          const message =
            nextError instanceof Error ? nextError.message : "Request failed";
          setError(message);
          setOverview(null);
          setShipments([]);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }

    void loadShippingData();

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

  async function handleShipmentAction(shipment: ShipmentSummary) {
    const accessToken = token?.access_token;
    if (!accessToken) {
      return;
    }

    const action = shippingActionPayload(shipment.status);
    if (!action) {
      return;
    }

    setPendingShipmentId(shipment.shipment_id);
    setError(null);

    try {
      await updateShipmentStatus(
        shipment.shipment_id,
        accessToken,
        action.body,
      );
      const [overviewResponse, shipmentResponse] = await Promise.all([
        fetchShippingOverview(accessToken),
        fetchShipments(accessToken),
      ]);
      setOverview(overviewResponse);
      setShipments(shipmentResponse);
    } catch (nextError) {
      const message =
        nextError instanceof Error ? nextError.message : "Request failed";
      setError(message);
    } finally {
      setPendingShipmentId(null);
    }
  }

  return (
    <div className="grid gap-6 xl:grid-cols-[1fr_320px]">
      <Card className="overflow-hidden shadow-[0_18px_48px_rgba(25,54,46,0.06)]">
        <div className="border-b border-[var(--in-border)] px-6 py-5">
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div>
              <h2 className="text-xl font-black text-[var(--in-text)]">
                Shipping operations
              </h2>
              <p className="mt-2 text-sm text-[var(--in-muted)]">
                출고 이후 배송 상태, ETA, 마지막 이벤트를 운영자가 바로 갱신하는
                downstream 배송 surface다.
              </p>
            </div>
            <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 board
              <ArrowUpRight className="h-4 w-4" />
            </Link>
          </div>
        </div>

        <table className="w-full border-collapse text-sm">
          <thead className="bg-[#faf6ef] text-left text-[var(--in-muted)]">
            <tr>
              {["Shipment", "Carrier", "Status", "ETA", "Action"].map((cell) => (
                <th
                  key={cell}
                  className="border-b border-[var(--in-border)] px-6 py-4 font-semibold"
                >
                  {cell}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td
                  className="border-b border-[var(--in-border)] px-6 py-4 text-[var(--in-muted)]"
                  colSpan={5}
                >
                  배송 shipment를 불러오는 중입니다.
                </td>
              </tr>
            ) : null}
            {error ? (
              <tr>
                <td
                  className="border-b border-[var(--in-border)] px-6 py-4 text-[#9d4d26]"
                  colSpan={5}
                >
                  {error}
                </td>
              </tr>
            ) : null}
            {!loading && !error && !shipments.length ? (
              <tr>
                <td
                  className="border-b border-[var(--in-border)] px-6 py-4 text-[var(--in-muted)]"
                  colSpan={5}
                >
                  현재 표시할 shipment가 없습니다.
                </td>
              </tr>
            ) : null}
            {shipments.map((shipment) => {
              const action = shippingActionPayload(shipment.status);
              return (
                <tr key={shipment.shipment_id}>
                  <td className="border-b border-[var(--in-border)] px-6 py-4">
                    <div className="font-semibold text-[var(--in-accent)]">
                      {shipment.shipment_id}
                    </div>
                    <div className="mt-1 text-xs text-[var(--in-muted)]">
                      {shipment.order_id} · {shipment.destination}
                    </div>
                    <div className="mt-1 text-xs text-[var(--in-muted)]">
                      {shipment.tracking_number}
                    </div>
                  </td>
                  <td className="border-b border-[var(--in-border)] px-6 py-4 text-[var(--in-muted)]">
                    <div className="font-semibold text-[var(--in-text)]">
                      {shipment.carrier}
                    </div>
                    <div className="mt-1 text-xs">{shipment.last_event}</div>
                  </td>
                  <td className="border-b border-[var(--in-border)] px-6 py-4">
                    <span
                      className={`rounded-full px-3 py-1 text-xs font-semibold ${shippingStatusClassName(
                        shipment.status,
                      )}`}
                    >
                      {shipment.status}
                    </span>
                  </td>
                  <td className="border-b border-[var(--in-border)] px-6 py-4 text-[var(--in-text)]">
                    {shipment.eta}
                  </td>
                  <td className="border-b border-[var(--in-border)] px-6 py-4">
                    {action ? (
                      <Button
                        size="sm"
                        variant={action.variant}
                        disabled={pendingShipmentId === shipment.shipment_id}
                        onClick={() => void handleShipmentAction(shipment)}
                      >
                        {pendingShipmentId === shipment.shipment_id
                          ? "처리 중"
                          : action.label}
                      </Button>
                    ) : (
                      <span className="text-xs font-semibold text-[var(--in-muted)]">
                        종료됨
                      </span>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>

      <div className="space-y-6">
        <Card className="p-6 shadow-[0_18px_48px_rgba(25,54,46,0.06)]">
          <p className="text-sm font-semibold uppercase tracking-[0.16em] text-[var(--in-accent)]">
            Shipping pulse
          </p>
          <p className="mt-3 text-2xl font-black text-[var(--in-text)]">
            {overview?.highlighted_route ?? "Route unavailable"}
          </p>
          <div className="mt-6 grid gap-3">
            {(overview?.stats ?? []).map((stat) => (
              <div
                key={stat.label}
                className="rounded-[22px] border border-[var(--in-border)] bg-white px-4 py-4"
              >
                <div className="flex items-center justify-between gap-3">
                  <span className="text-sm text-[var(--in-muted)]">
                    {stat.label}
                  </span>
                  {stat.label === "지연" ? (
                    <AlertTriangle className="h-4 w-4 text-[#c4663a]" />
                  ) : stat.label === "오늘 완료" ? (
                    <CircleCheckBig className="h-4 w-4 text-[#245f92]" />
                  ) : (
                    <Truck className="h-4 w-4 text-[var(--in-accent)]" />
                  )}
                </div>
                <div className="mt-3 text-2xl font-black text-[var(--in-text)]">
                  {stat.value}
                </div>
              </div>
            ))}
            {loading && !overview ? (
              <div className="text-sm text-[var(--in-muted)]">
                배송 overview를 불러오는 중입니다.
              </div>
            ) : null}
          </div>
        </Card>

        <Card className="p-6 shadow-[0_18px_48px_rgba(25,54,46,0.06)]">
          <h2 className="text-xl font-black text-[var(--in-text)]">
            Carrier load
          </h2>
          <div className="mt-5 space-y-3">
            {!loading && !error && !(overview?.carriers.length ?? 0) ? (
              <div className="text-sm text-[var(--in-muted)]">
                표시할 carrier 데이터가 없습니다.
              </div>
            ) : null}
            {(overview?.carriers ?? []).map((carrier) => (
              <div
                key={carrier.label}
                className="rounded-[22px] border border-[var(--in-border)] bg-white px-4 py-4"
              >
                <div className="font-semibold text-[var(--in-text)]">
                  {carrier.label}
                </div>
                <div className="mt-1 text-sm text-[var(--in-muted)]">
                  {carrier.value}
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}
