"use client";

import { ReactNode } from "react";
import {
  AlertTriangle,
  Ban,
  Download,
  RefreshCw,
  Settings,
  ShieldCheck,
  Smartphone,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/use-toast";
import { useAppInfo } from "@/lib/platform/app-info";
import { useCapability, type Capability, type CapabilityState, type UseCapability } from "@/lib/platform/capabilities";
import { getPlatformServices } from "@/lib/platform/services";
import AppDownloadLinks from "./app-download-links";

interface CapabilityGateProps {
  capability: Capability;
  /** Rendered once the capability is available. */
  children: ReactNode | ((api: UseCapability) => ReactNode);
  /** Otherwise: "notice" (why, and what to do; default), "hidden", or your own node. */
  fallback?: "notice" | "hidden" | ReactNode;
}

/** Wraps anything that needs a device feature; everywhere it is missing gets a clear message. */
export default function CapabilityGate({ capability, children, fallback = "notice" }: CapabilityGateProps) {
  const api = useCapability(capability);
  const { state } = api;

  if (state?.status === "available") {
    return <>{typeof children === "function" ? children(api) : children}</>;
  }

  if (fallback === "hidden") return null;
  if (fallback !== "notice") return <>{fallback}</>;
  if (!state) return <div className="h-24 w-full rounded-2xl bg-muted animate-pulse" />;

  return <CapabilityNotice capability={capability} state={state} api={api} />;
}

interface NoticeProps {
  capability: Capability;
  state: CapabilityState;
  api: UseCapability;
}

export function CapabilityNotice({ capability, state, api }: NoticeProps) {
  const { platform } = useAppInfo();
  const services = getPlatformServices();

  const failToast = (description: string) =>
    toast({ title: "خطا", description, variant: "error" });

  switch (state.status) {
    case "unsupported-platform":
      if (platform === "web") {
        return (
          <NoticeCard icon={<Smartphone />} title={capability.title}>
            این امکان فقط در اپلیکیشن موبایل رنگوک در دسترس است.
            <AppDownloadLinks />
          </NoticeCard>
        );
      }
      return (
        <NoticeCard icon={<Ban />} title={capability.title}>
          این امکان روی {platform === "ios" ? "iOS" : "اندروید"} در دسترس نیست.
        </NoticeCard>
      );

    case "unsupported-device":
      return (
        <NoticeCard icon={<Ban />} title={capability.title}>
          گوشی شما از این امکان پشتیبانی نمی‌کند.
        </NoticeCard>
      );

    case "needs-app-update":
      return (
        <NoticeCard
          icon={<RefreshCw />}
          title={capability.title}
          action={{
            label: "بروزرسانی اپلیکیشن",
            run: async () => {
              if (!(await services.openAppUpdatePage())) failToast("صفحه بروزرسانی باز نشد.");
            },
          }}
        >
          برای استفاده از این امکان، رنگوک را به آخرین نسخه بروزرسانی کنید.
        </NoticeCard>
      );

    case "needs-install":
      return (
        <NoticeCard
          icon={<Download />}
          title={capability.title}
          action={
            state.installUrl
              ? {
                label: `نصب ${state.installName ?? ""}`.trim(),
                run: async () => {
                  if (!(await services.openExternal(state.installUrl!))) failToast("صفحه نصب باز نشد.");
                },
              }
              : undefined
          }
        >
          برای استفاده از این امکان، ابتدا {state.installName ?? "برنامه مورد نیاز"} را روی گوشی نصب کنید.
        </NoticeCard>
      );

    case "needs-permission":
      return (
        <NoticeCard icon={<ShieldCheck />} title={capability.title} action={{ label: "اجازه دادن", run: api.request }}>
          رنگوک برای این امکان به اجازه شما نیاز دارد.
        </NoticeCard>
      );

    case "permission-denied":
      return (
        <NoticeCard
          icon={<Settings />}
          title={capability.title}
          action={{
            label: "باز کردن تنظیمات",
            run: async () => {
              if (!(await services.openAppSettings())) failToast("تنظیمات گوشی باز نشد.");
            },
          }}
        >
          دسترسی لازم داده نشده است. می‌توانید آن را از تنظیمات گوشی برای رنگوک فعال کنید.
        </NoticeCard>
      );

    case "error":
    default:
      return (
        <NoticeCard icon={<AlertTriangle />} title={capability.title} action={{ label: "تلاش مجدد", run: api.refresh }}>
          بررسی این امکان با مشکل مواجه شد.
        </NoticeCard>
      );
  }
}

interface NoticeCardProps {
  icon: ReactNode;
  title: string;
  children: ReactNode;
  action?: { label: string; run: () => void | Promise<void> };
}

function NoticeCard({ icon, title, children, action }: NoticeCardProps) {
  return (
    <div className="w-full flex flex-col items-center text-center p-5 rounded-2xl border border-line bg-card shadow-sm">
      <div className="w-12 h-12 flex items-center justify-center rounded-2xl bg-sienna-soft text-primary [&>svg]:w-6 [&>svg]:h-6">
        {icon}
      </div>

      <h3 className="mt-3 font-semibold text-sm text-foreground">{title}</h3>

      <div className="mt-1 w-full text-xs text-muted-foreground leading-relaxed">{children}</div>

      {action && (
        <Button className="mt-4 w-full rounded-xl" onClick={() => { void action.run(); }}>
          {action.label}
        </Button>
      )}
    </div>
  );
}
