"use client";

import Link from "next/link";
import { Rocket, MapPin } from "lucide-react";
import { Button, Card, CardContent, Badge, EmptyState } from "@/components/ds";
import { useDeliveryCapabilities } from "@/modules/delivery/hooks/useDeliveryCapabilities";
import { DeliveryPageLoader, DeliveryPageError } from "@/modules/delivery/pages/shared";
import { DeliveryBreadcrumbs } from "@/modules/delivery/components/DeliveryBreadcrumbs";
import type { PhaseGateConfig } from "@/modules/delivery/types";

export function DeliveryPhaseGate({
  config,
  children,
  showMapHint,
}: {
  config: PhaseGateConfig;
  children?: React.ReactNode;
  showMapHint?: boolean;
}) {
  const caps = useDeliveryCapabilities();

  if (caps.isLoading) return <DeliveryPageLoader label="بررسی قابلیت‌ها…" />;
  if (caps.error) return <DeliveryPageError error={caps.error} onRetry={() => caps.refetch()} />;

  const enabled = caps.data?.features?.[config.feature] === true;
  if (enabled && children) return <>{children}</>;

  return (
    <div className="space-y-4">
      <DeliveryBreadcrumbs current={config.title} />
      <Card>
        <CardContent className="flex flex-col items-center gap-4 p-8 text-center">
          <div className="rounded-full bg-[var(--delivery-accent-soft)] p-4">
            {showMapHint ? (
              <MapPin className="h-8 w-8 text-[var(--delivery-accent)]" />
            ) : (
              <Rocket className="h-8 w-8 text-[var(--delivery-accent)]" />
            )}
          </div>
          <div>
            <h2 className="text-xl font-bold text-secondary">{config.title}</h2>
            <p className="mt-2 max-w-lg text-sm text-[var(--muted)]">{config.description}</p>
          </div>
          <Badge tone="info">فاز {config.phase}</Badge>
          <p className="text-xs text-[var(--muted)]">
            این قابلیت پس از فعال‌سازی در backend از طریق{" "}
            <code className="rounded bg-[var(--surface-muted)] px-1">/capabilities</code> در دسترس خواهد بود.
          </p>
          <div className="flex flex-wrap gap-2">
            <Link href="/delivery/capabilities">
              <Button variant="outline">مشاهده قابلیت‌ها</Button>
            </Link>
            <Link href="/delivery">
              <Button>بازگشت به داشبورد</Button>
            </Link>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

export function createDeliveryPhasePage(config: PhaseGateConfig, showMapHint = false) {
  return function DeliveryPhasePage() {
    return <DeliveryPhaseGate config={config} showMapHint={showMapHint} />;
  };
}
