"use client";

import { useEffect, useState } from "react";
import { api, Pricing } from "@/lib/api";
import { useApi } from "@/hooks/useApi";
import { useLocale } from "@/i18n/LocaleProvider";
import {
  Button,
  Card,
  ErrorState,
  Field,
  IconChip,
  MoneyText,
  Numeric,
  PageHeader,
  SectionTitle,
  SkeletonCard,
} from "@/components/ui";

/**
 * Live pricing. Editing publishes a new plan; rides already under way keep the price they were
 * quoted (the snapshot is enforced in booking-service), so this form changes future rides only.
 */
export default function Page() {
  const state = useApi<Pricing>(api.getPricing, []);

  return (
    <div>
      <PageHeader titleKey="nav.pricing" />
      {state.loading ? (
        <SkeletonCard rows={5} />
      ) : state.error ? (
        <ErrorState onRetry={state.reload} />
      ) : state.data ? (
        <PricingEditor initial={state.data} onSaved={state.reload} />
      ) : null}
    </div>
  );
}

function PricingEditor({
  initial,
  onSaved,
}: {
  initial: Pricing;
  onSaved: () => void;
}) {
  const { t } = useLocale();
  const [form, setForm] = useState(initial);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [saved, setSaved] = useState(false);

  useEffect(() => setForm(initial), [initial]);

  const num = (v: string) => (v === "" ? 0 : Number(v));
  const dirty = JSON.stringify(form) !== JSON.stringify(initial);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true);
    setError(null);
    setSaved(false);
    try {
      await api.updatePricing(form);
      setSaved(true);
      onSaved();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    } finally {
      setBusy(false);
    }
  };

  const currency = form.currency || "SAR";

  return (
    <div className="grid gap-6 lg:grid-cols-[1fr_320px]">
      <Card>
        <SectionTitle>{t("pricing.title")}</SectionTitle>
        <p className="mb-6 text-sm text-muted">{t("pricing.subtitle")}</p>

        <form onSubmit={submit} className="space-y-4">
          <Field
            label={t("pricing.unlockFee")}
            type="number"
            step="0.01"
            min="0"
            value={String(form.unlockFee)}
            onChange={(e) => setForm({ ...form, unlockFee: num(e.target.value) })}
            icon={<span className="text-xs">{currency}</span>}
          />
          <Field
            label={t("pricing.perMinute")}
            type="number"
            step="0.01"
            min="0"
            value={String(form.perMinuteRate)}
            onChange={(e) => setForm({ ...form, perMinuteRate: num(e.target.value) })}
            icon={<span className="text-xs">{currency}</span>}
          />
          <Field
            label={t("pricing.minBalance")}
            type="number"
            step="0.01"
            min="0"
            value={String(form.minStartBalance)}
            onChange={(e) => setForm({ ...form, minStartBalance: num(e.target.value) })}
            icon={<span className="text-xs">{currency}</span>}
          />
          <div>
            <Field
              label={t("pricing.maxDuration")}
              type="number"
              min="1"
              placeholder={t("pricing.noCap")}
              value={form.maxRideMinutes == null ? "" : String(form.maxRideMinutes)}
              onChange={(e) =>
                setForm({
                  ...form,
                  maxRideMinutes: e.target.value === "" ? null : Number(e.target.value),
                })
              }
              icon={<span className="text-xs">min</span>}
            />
            <p className="mt-1.5 text-xs text-muted">{t("pricing.maxDurationHint")}</p>
          </div>

          {error && (
            <div className="tint tone-danger rounded-card border p-3 text-sm">{error}</div>
          )}
          {saved && !dirty && (
            <div className="tint tone-success rounded-card border p-3 text-sm">
              {t("pricing.saved")}
            </div>
          )}

          <Button variant="primary" type="submit" disabled={busy || !dirty} className="w-full">
            {busy ? t("common.loading") : t("pricing.save")}
          </Button>
        </form>
      </Card>

      {/* A worked example so the operator sees what a change means before saving. */}
      <FarePreview pricing={form} />
    </div>
  );
}

function FarePreview({ pricing }: { pricing: Pricing }) {
  const { t } = useLocale();
  const minutes = 15;
  const fare = pricing.unlockFee + pricing.perMinuteRate * minutes;
  const currency = pricing.currency || "SAR";

  return (
    <Card>
      <div className="flex items-center gap-3">
        <IconChip tone="brand">⛁</IconChip>
        <SectionTitle>{t("pricing.exampleTitle")}</SectionTitle>
      </div>
      <p className="mt-1 text-sm text-muted">{t("pricing.exampleSubtitle")}</p>

      <div className="mt-4 card divide-y divide-line">
        <Row label={t("pricing.unlockFee")} value={<MoneyText amount={pricing.unlockFee} currency={currency} />} />
        <Row
          label={`${pricing.perMinuteRate.toFixed(2)} × ${minutes} min`}
          value={<MoneyText amount={pricing.perMinuteRate * minutes} currency={currency} />}
        />
      </div>

      <div className="mt-4 flex items-center justify-between">
        <span className="text-sm text-muted">{t("pricing.exampleTotal")}</span>
        <span className="text-2xl font-bold text-brand">
          <Numeric>{fare.toFixed(2)}</Numeric>{" "}
          <span className="text-sm font-normal text-muted">{currency}</span>
        </span>
      </div>
    </Card>
  );
}

function Row({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex items-center justify-between px-4 py-3">
      <span className="text-sm text-muted">{label}</span>
      {value}
    </div>
  );
}
