"use client";

import { useState } from "react";
import { Download, Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Drawer,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
} from "@/components/ui/drawer";
import { useAppInfo } from "@/lib/platform/app-info";
import { channelLabel } from "@/lib/platform/channels";
import { openUpdate } from ".";
import type { UpdateOffer } from "./policy";
import { snoozeOptionalUpdate, useNativeUpdateState } from "./state";

/** The apps' update UI, rendered once by the native shell. */
export default function NativeUpdatePrompt() {
  const state = useNativeUpdateState();

  if (state.kind === "required") return <RequiredUpdateScreen offer={state.offer} />;
  if (state.kind === "optional") return <OptionalUpdateSheet offer={state.offer} />;
  return null;
}

function actionLabel(offer: UpdateOffer): string {
  if (offer.channel === "direct") return "دانلود نسخه جدید";
  const store = channelLabel(offer.channel);
  return store ? `بروزرسانی از ${store}` : "بروزرسانی";
}

function useOpenUpdate(offer: UpdateOffer) {
  const [failed, setFailed] = useState(false);
  const [opening, setOpening] = useState(false);

  const open = async () => {
    setOpening(true);
    setFailed(!(await openUpdate(offer)));
    setOpening(false);
  };

  return { open, opening, failed };
}

/** Below minimumBuild: covers the app and cannot be dismissed. */
function RequiredUpdateScreen({ offer }: { offer: UpdateOffer }) {
  const info = useAppInfo();
  const { open, opening, failed } = useOpenUpdate(offer);

  return (
    <div
      role="alertdialog"
      aria-modal="true"
      aria-labelledby="required-update-title"
      className="fixed inset-0 z-[1000] flex justify-center bg-background"
    >
      <div className="w-full max-w-[480px] flex flex-col px-6 py-10 text-center">
        <div className="flex-1 flex flex-col items-center justify-center">
          <div className="mb-6 w-20 h-20 rounded-3xl bg-sienna-soft border border-line flex items-center justify-center">
            <Download className="w-10 h-10 text-primary" />
          </div>

          <h1 id="required-update-title" className="text-xl font-bold text-foreground">
            بروزرسانی ضروری
          </h1>

          <p className="mt-3 text-sm text-muted-foreground leading-relaxed">
            این نسخه از رنگوک دیگر پشتیبانی نمی‌شود. برای ادامه، نسخه {offer.latestVersion} را نصب کنید.
          </p>

          <ReleaseNotes notes={offer.notes} />
        </div>

        <div className="flex flex-col">
          {offer.channel === "direct" && (
            <p className="mb-3 text-xs text-muted-foreground leading-relaxed">
              پس از پایان دانلود، فایل را باز کنید و گزینه نصب را بزنید.
            </p>
          )}

          {failed && <OpenFailedNotice offer={offer} />}

          <Button size="lg" className="w-full rounded-xl" onClick={open} disabled={opening}>
            {actionLabel(offer)}
          </Button>

          {info.native && (
            <span className="mt-4 text-xs text-muted-foreground" dir="ltr">
              {info.native.version} ({info.native.build})
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

/** A newer build exists. Dismissing it snoozes that build for a day. */
function OptionalUpdateSheet({ offer }: { offer: UpdateOffer }) {
  const { open, opening, failed } = useOpenUpdate(offer);

  return (
    <Drawer
      open
      onOpenChange={(isOpen) => {
        if (!isOpen) snoozeOptionalUpdate(offer);
      }}
    >
      <DrawerContent className="mx-auto w-full max-w-[480px]">
        <DrawerHeader className="text-center">
          <div className="mx-auto mb-2 w-12 h-12 rounded-2xl bg-sienna-soft flex items-center justify-center">
            <Sparkles className="w-6 h-6 text-primary" />
          </div>
          <DrawerTitle className="text-center">نسخه جدید رنگوک</DrawerTitle>
          <DrawerDescription className="text-center">
            نسخه {offer.latestVersion} منتشر شده است.
          </DrawerDescription>
          <ReleaseNotes notes={offer.notes} />
        </DrawerHeader>

        <DrawerFooter>
          {failed && <OpenFailedNotice offer={offer} />}

          <Button size="lg" className="w-full rounded-xl" onClick={open} disabled={opening}>
            {actionLabel(offer)}
          </Button>
          <Button
            size="lg"
            variant="ghost"
            className="w-full rounded-xl"
            onClick={() => snoozeOptionalUpdate(offer)}
          >
            بعداً
          </Button>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  );
}

function ReleaseNotes({ notes }: { notes: string[] }) {
  if (!notes.length) return null;

  return (
    <ul className="mt-4 w-full rounded-xl bg-muted p-4 text-right text-sm text-foreground flex flex-col [&>*:not(:last-child)]:mb-1.5">
      {notes.map((note, index) => (
        <li key={index} className="flex">
          <span className="ml-2 text-primary">•</span>
          <span>{note}</span>
        </li>
      ))}
    </ul>
  );
}

// Neither the store nor the browser opened.
function OpenFailedNotice({ offer }: { offer: UpdateOffer }) {
  const store = channelLabel(offer.channel);

  return (
    <p className="mb-3 text-xs text-destructive leading-relaxed">
      صفحه بروزرسانی باز نشد.
      {store ? ` لطفاً رنگوک را از ${store} بروزرسانی کنید.` : " لطفاً بعداً دوباره تلاش کنید."}
    </p>
  );
}
