"use client";

import { useState } from "react";
import {
  Check,
  CheckCircle2,
  ChevronRight,
  Crown,
  Download,
  X,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Field, SelectField } from "@/components/shared/field";
import {
  DetailList,
  Panel,
  PreviewNotice,
  StatusBadge,
} from "@/components/shared/page";
import {
  PreviewLink,
  usePreviewRole,
} from "@/components/layout/preview-context";
import { canManage } from "@/lib/preview";
import {
  connectorError,
  featureComparison,
  formatPlanPrice,
  subscriptionAddons,
  subscriptionFixture,
  subscriptionHistory,
  subscriptionPlans,
  subscriptionTotal,
  type Currency,
  type PlanId,
} from "./model";
export function SubscriptionPreview({ portal = false }: { portal?: boolean }) {
  const role = usePreviewRole();
  const editable = portal || canManage(role);
  const [currency, setCurrency] = useState<Currency>("IDR");
  const [count, setCount] = useState<number>(subscriptionFixture.connectors);
  const [selected, setSelected] = useState<PlanId | null>(null);
  const [addons, setAddons] = useState<string[]>([]);
  const [review, setReview] = useState(false);
  const [cancel, setCancel] = useState(false);
  const [cancelled, setCancelled] = useState(false);
  const [feedback, setFeedback] = useState("");
  const plan = subscriptionPlans.find((item) => item.id === selected);
  const validation = plan ? connectorError(plan, count) : undefined;
  const totals =
    plan && !validation
      ? subscriptionTotal(
          plan,
          count,
          currency,
          subscriptionAddons.filter((item) => addons.includes(item.id)),
        )
      : undefined;
  function choose(id: PlanId) {
    setSelected(id);
    setAddons([]);
    setFeedback("");
  }
  function downloadInvoice(id: string) {
    const invoice = subscriptionHistory.find((item) => item.id === id);
    if (!invoice) return;
    const blob = new Blob(
      [
        `TIAR — LOCAL PREVIEW INVOICE\n${invoice.id}\n${invoice.date}\n${invoice.plan} · ${invoice.connectors} connectors\n${formatPlanPrice(invoice.amount, "IDR")}\nNo payment was processed. This fixture is not a tax invoice.`,
      ],
      {
        type: "text/plain;charset=utf-8",
      },
    );
    const href = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = href;
    a.download = `${id}.txt`;
    a.click();
    URL.revokeObjectURL(href);
    setFeedback(
      "Preview invoice downloaded. It is a local fixture, not a payment receipt.",
    );
  }
  return (
    <div className="space-y-6">
      <PreviewNotice>
        Local subscription preview. Prices, connector counts, and invoices are
        sample data. No checkout, activation, cancellation, or charge is
        performed.
      </PreviewNotice>
      {!portal && (
        <Panel title="Active Subscription">
          <div className="flex flex-wrap items-center justify-between gap-4 p-5">
            <div className="flex items-center gap-4">
              <span className="rounded-xl bg-primary/10 p-3 text-primary">
                <Crown size={26} />
              </span>
              <div>
                <h2 className="text-xl font-semibold">Professional</h2>
                <p className="mt-1 text-sm text-muted-foreground">
                  {subscriptionFixture.organization}
                </p>
              </div>
            </div>
            <StatusBadge>
              {cancelled ? "Cancelled preview" : "Active"}
            </StatusBadge>
          </div>
          <DetailList
            items={{
              "Billing period": subscriptionFixture.period,
              "Next billing": cancelled
                ? "Cancelled locally"
                : subscriptionFixture.nextBilling,
              "Connected connectors": subscriptionFixture.connectors,
              "Monthly amount": formatPlanPrice(2880000, "IDR"),
            }}
          />
        </Panel>
      )}
      <div className="flex flex-wrap items-end justify-between gap-4">
        <div>
          <h2 className="text-2xl font-semibold">Choose Your Plan</h2>
          <p className="mt-2 text-sm text-muted-foreground">
            The right tools to grow your EV charging business.
          </p>
        </div>
        <div className="flex flex-wrap gap-3">
          <div className="w-44">
            <Field
              label="Preview connectors"
              type="number"
              min={1}
              max={100000}
              step={1}
              value={Number.isNaN(count) ? "" : count}
              onChange={(event) => {
                setCount(event.target.valueAsNumber);
                setReview(false);
              }}
            />
          </div>
          <div className="w-28">
            <SelectField
              label="Currency"
              value={currency}
              options={["IDR", "USD"]}
              onChange={(event) =>
                setCurrency(event.target.value === "USD" ? "USD" : "IDR")
              }
            />
          </div>
        </div>
      </div>
      {!editable && (
        <PreviewNotice>
          This role can review subscriptions. Switch to the Admin preview
          to select a plan.
        </PreviewNotice>
      )}
      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        {subscriptionPlans.map((item) => (
          <section
            key={item.id}
            className={`panel relative flex flex-col overflow-hidden ${selected === item.id ? "ring-2 ring-primary" : item.highlighted ? "border-primary" : ""}`}
          >
            <div
              className={`h-1 ${item.highlighted ? "bg-primary" : "bg-muted"}`}
            />
            <div className="flex flex-1 flex-col p-5">
              {item.highlighted && (
                <span className="mb-3 text-xs font-semibold tracking-wide text-primary">
                  MOST POPULAR
                </span>
              )}
              <h3 className="text-xl font-semibold">{item.name}</h3>
              <p className="mt-2 min-h-10 text-sm leading-5 text-muted-foreground">
                {item.description}
              </p>
              <div className="mt-5 text-2xl font-semibold">
                {formatPlanPrice(item.price[currency], currency)}
              </div>
              <p className="mt-1 text-xs text-muted-foreground">
                per connector / month
              </p>
              <p className="mt-4 text-sm font-medium">
                {item.maximum
                  ? `${item.minimum}–${item.maximum} connectors`
                  : `${item.minimum}+ connectors`}
              </p>
              <ul className="mt-5 mb-6 flex-1 space-y-3 text-sm">
                {item.features.map((feature) => (
                  <li className="flex gap-2" key={feature}>
                    <Check size={16} className="mt-0.5 shrink-0 text-primary" />
                    {feature}
                  </li>
                ))}
              </ul>
              <Button
                disabled={!editable}
                variant={selected === item.id ? "default" : "outline"}
                onClick={() => choose(item.id)}
              >
                {selected === item.id ? "Selected" : "Select Plan"}
                <ChevronRight size={16} />
              </Button>
            </div>
          </section>
        ))}
      </div>
      <Panel
        title="Features & Add-ons"
        description="Compare core capabilities and explore optional white label features."
      >
        <div className="overflow-x-auto">
          <table className="data-table">
            <thead>
              <tr>
                <th>Features</th>
                {subscriptionPlans.map((item) => (
                  <th key={item.id}>{item.name}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {featureComparison.map((feature) => (
                <tr key={feature.name}>
                  <td>{feature.name}</td>
                  {feature.included.map((included, i) => (
                    <td key={i}>
                      {included ? (
                        <Check
                          size={17}
                          className="text-success"
                          aria-label="Included"
                        />
                      ) : (
                        <X
                          size={17}
                          className="text-muted-foreground"
                          aria-label="Not included"
                        />
                      )}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="grid gap-3 border-t p-5 sm:grid-cols-2">
          {subscriptionAddons.map((addon) => (
            <label
              className="flex cursor-pointer items-start gap-3 rounded-xl border p-4"
              key={addon.id}
            >
              <input
                type="checkbox"
                className="mt-1 accent-primary"
                disabled={!plan || !editable}
                checked={addons.includes(addon.id)}
                onChange={(event) =>
                  setAddons(
                    event.target.checked
                      ? [...addons, addon.id]
                      : addons.filter((id) => id !== addon.id),
                  )
                }
              />
              <span>
                <span className="font-medium">{addon.name}</span>
                <span className="mt-1 block text-xs text-muted-foreground">
                  {formatPlanPrice(addon.price[currency], currency)} ·{" "}
                  {addon.billing === "monthly" ? "per month" : "one time"}
                </span>
              </span>
            </label>
          ))}
        </div>
      </Panel>
      {plan && (
        <Panel title="Your Selection">
          <DetailList
            items={{
              Plan: plan.name,
              Connectors: Number.isNaN(count) ? "Enter a count" : count,
              "Monthly total": totals
                ? formatPlanPrice(totals.monthly, currency)
                : "Unavailable",
              "One-time add-ons": totals
                ? formatPlanPrice(totals.oneTime, currency)
                : "Unavailable",
            }}
          />
          <div className="space-y-3 border-t p-5">
            {validation && (
              <p role="alert" className="text-sm text-destructive">
                {validation}
              </p>
            )}
            <p className="text-xs text-muted-foreground">
              Connector eligibility is evaluated using local fixtures. Actual
              availability requires backend validation in a later phase.
            </p>
            <Button
              disabled={!!validation || !editable}
              onClick={() => setReview(true)}
            >
              Review selection
            </Button>
          </div>
        </Panel>
      )}
      {!portal && (
        <>
          <Panel title="Subscription History">
            <div className="overflow-x-auto">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>Invoice</th>
                    <th>Plan</th>
                    <th>Date</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th aria-label="Download invoice" />
                  </tr>
                </thead>
                <tbody>
                  {subscriptionHistory.map((invoice) => (
                    <tr key={invoice.id}>
                      <td className="font-medium">{invoice.id}</td>
                      <td>{invoice.plan}</td>
                      <td>{invoice.date}</td>
                      <td>{formatPlanPrice(invoice.amount, "IDR")}</td>
                      <td>
                        <StatusBadge>{invoice.status}</StatusBadge>
                      </td>
                      <td>
                        <Button
                          size="icon"
                          variant="ghost"
                          aria-label={`Download ${invoice.id} preview invoice`}
                          onClick={() => downloadInvoice(invoice.id)}
                        >
                          <Download size={17} />
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Panel>
          <Panel
            title="Cancel Subscription"
            description="Review the cancellation state using this local preview."
          >
            <div className="flex flex-wrap items-center justify-between gap-4 p-5">
              <p className="max-w-xl text-sm text-muted-foreground">
                Cancellation can affect premium features and connector access.
                This demonstration only changes the status on this page.
              </p>
              <Button
                variant="destructive"
                disabled={!editable || cancelled}
                onClick={() => setCancel(true)}
              >
                {cancelled ? "Cancelled in preview" : "Cancel Subscription"}
              </Button>
            </div>
          </Panel>
        </>
      )}
      {feedback && <PreviewNotice>{feedback}</PreviewNotice>}
      <Dialog open={review} onOpenChange={setReview}>
        <DialogContent>
          <DialogTitle>Review Your Selection</DialogTitle>
          <DialogDescription>
            Review sample pricing before exploring a payment outcome. No payment
            provider will open.
          </DialogDescription>
          {plan && totals && (
            <DetailList
              items={{
                Plan: plan.name,
                Connectors: count,
                "Monthly total": formatPlanPrice(totals.monthly, currency),
                "One-time total": formatPlanPrice(totals.oneTime, currency),
              }}
            />
          )}
          <PreviewNotice>
            Payment outcomes are visual demonstrations. They do not verify
            payment or activate service.
          </PreviewNotice>
          <DialogFooter>
            <Button variant="outline" onClick={() => setReview(false)}>
              Back
            </Button>
            <Button asChild variant="outline">
              <PreviewLink href="/subscription/failed">
                Preview failure
              </PreviewLink>
            </Button>
            <Button asChild>
              <PreviewLink href="/subscription/success">
                <CheckCircle2 size={16} />
                Preview success
              </PreviewLink>
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      <Dialog open={cancel} onOpenChange={setCancel}>
        <DialogContent>
          <DialogTitle>Cancel Professional Subscription?</DialogTitle>
          <DialogDescription>
            In the live system, cancellation may affect premium features,
            connector limits, and support. Here it changes only the local card
            state.
          </DialogDescription>
          <DialogFooter>
            <Button variant="outline" onClick={() => setCancel(false)}>
              Keep Subscription
            </Button>
            <Button
              variant="destructive"
              onClick={() => {
                setCancelled(true);
                setCancel(false);
                setFeedback(
                  "Subscription cancellation preview completed. No subscription was changed. Reload restores the sample active state.",
                );
              }}
            >
              Confirm local cancellation
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
