import { FormEventHandler, useState } from 'react';

import { Head, useForm, usePage } from '@inertiajs/react';

import InputError from '@/Components/InputError';
import EditorialPageHeader from '@/Components/layout/EditorialPageHeader';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import { Switch } from '@/Components/ui/switch';
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { formatCurrency } from '@/lib/format';
import type { PageProps } from '@/types';

interface Props {
  /** Current effective portfolio cap (USD). null when the plan is unlimited. */
  portfolio_cap: number | null;
  /** Plan ceiling (USD) the cap may not exceed. null = unlimited plan. */
  plan_max: number | null;
  /** The resolved plan-tier default cap (USD) applied when portfolio_cap is null/blank.
   *  null = unlimited plan (no default cap). */
  plan_default_cap: number | null;
  /** Month-to-date portfolio spend (USD), for context. */
  mtd_spend: number;
}

export default function Budget({ portfolio_cap, plan_max, plan_default_cap, mtd_spend }: Props) {
  const { auth } = usePage<PageProps>().props;
  void auth;

  const unlimited = plan_max === null;

  // A cap of exactly 0 means "pause all AI spend" — surface it as an explicit,
  // labeled toggle instead of expecting the user to know the magic value.
  const [paused, setPaused] = useState<boolean>(portfolio_cap === 0);

  // Remember the last non-zero cap so toggling pause off restores it instead of
  // clearing the field.
  const [lastCap, setLastCap] = useState<string>(
    portfolio_cap !== null && portfolio_cap > 0 ? String(portfolio_cap) : '',
  );

  const { data, setData, put, processing, errors, isDirty, transform } = useForm<{
    cap_usd: string;
  }>({
    cap_usd: portfolio_cap !== null ? String(portfolio_cap) : '',
  });

  const dirty = isDirty || paused !== (portfolio_cap === 0);

  useUnsavedChanges(dirty);

  const togglePause = (next: boolean) => {
    setPaused(next);
    if (next) {
      // Stash the current cap, then set the form value to 0 (the paused state).
      if (data.cap_usd !== '' && data.cap_usd !== '0') {
        setLastCap(data.cap_usd);
      }
      setData('cap_usd', '0');
    } else {
      // Restore the last non-zero cap (or clear back to the plan default).
      setData('cap_usd', lastCap);
    }
  };

  const submit: FormEventHandler = (e) => {
    e.preventDefault();
    // When paused, always submit a 0 cap regardless of the (hidden) input value.
    transform((d) => ({ ...d, cap_usd: paused ? '0' : d.cap_usd }));
    // Inertia useForm.put manages its own request lifecycle — do NOT await.
    put(route('settings.budget.portfolio'), { preserveScroll: true });
  };

  return (
    <DashboardLayout>
      <Head title="Budget" />

      <div className="container py-8">
        <EditorialPageHeader
          eyebrow="SETTINGS"
          title="Budget"
          subtitle="Set a hard monthly cap on your AI spend. Batches that would exceed it are blocked before they run."
        />

        <div className="mt-8 max-w-xl">
          <Card variant="flat">
            <CardHeader>
              <CardTitle>Monthly spend cap</CardTitle>
              <CardDescription>
                {unlimited
                  ? 'Your plan has no spend cap. Set a number below to impose your own ceiling.'
                  : `Your plan allows a cap of up to ${formatCurrency(plan_max ?? 0)}.`}{' '}
                You&rsquo;ve spent {formatCurrency(mtd_spend)} so far this month.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={submit} className="space-y-4">
                <div className="flex items-center justify-between gap-3 rounded-md border border-border p-3">
                  <div className="space-y-1">
                    <Label htmlFor="pause_spend" className="cursor-pointer">
                      Pause all AI spend
                    </Label>
                    <p className="text-xs text-foreground/70">
                      Temporarily blocks every new AI batch and draft. Your spend cap is kept and
                      restored when you unpause; your existing drafts are unaffected.
                    </p>
                  </div>
                  <Switch
                    id="pause_spend"
                    checked={paused}
                    onCheckedChange={togglePause}
                    aria-label="Pause all AI spend"
                  />
                </div>

                {!paused && (
                  <div className="space-y-2">
                    <Label htmlFor="cap_usd">Cap (USD per month)</Label>
                    {portfolio_cap === null && plan_default_cap !== null && (
                      <p className="text-xs text-muted-foreground">
                        Currently using plan default: <strong>{formatCurrency(plan_default_cap)}/mo</strong>
                      </p>
                    )}
                    <div className="relative">
                      <span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground">
                        $
                      </span>
                      <Input
                        id="cap_usd"
                        type="number"
                        min="0"
                        max={plan_max ?? undefined}
                        step="1"
                        inputMode="numeric"
                        className="pl-7"
                        value={data.cap_usd}
                        onChange={(e) => setData('cap_usd', e.target.value)}
                        placeholder="20"
                      />
                    </div>
                    <InputError message={errors.cap_usd} />
                    {/* F4UXA-010: inline over-cap warning when plan_max is exceeded */}
                    {plan_max !== null && data.cap_usd !== '' && Number(data.cap_usd) > plan_max && (
                      <p className="text-xs text-warning-high">
                        Your plan allows up to {formatCurrency(plan_max)} — lower the cap or upgrade.
                      </p>
                    )}
                    {/* F4UXA-010: redirect to pause toggle when user types 0 directly */}
                    {data.cap_usd === '0' && !paused && (
                      <p className="text-xs text-muted-foreground">
                        To stop all spend, use the <strong>Pause all AI spend</strong> toggle above rather than a $0 cap.
                      </p>
                    )}
                    <p className="text-xs text-foreground/70">
                      Once your month-to-date spend reaches the cap, new batches are blocked until
                      the cap is raised or the month resets.{' '}
                      {plan_default_cap !== null
                        ? `Leave blank to use your plan default (currently ${formatCurrency(plan_default_cap)}/mo).`
                        : 'Leave blank for unlimited spend (your plan has no cap).'}
                    </p>
                  </div>
                )}

                {paused && (
                  <>
                    <p className="text-xs italic text-foreground/70">
                      Your spend cap is saved. Unpause to view or adjust it.
                    </p>
                    <InputError message={errors.cap_usd} />
                  </>
                )}

                <LoadingButton type="submit" loading={processing} disabled={!dirty}>
                  {paused ? 'Save — AI spend paused' : 'Save cap'}
                </LoadingButton>
              </form>
            </CardContent>
          </Card>
        </div>
      </div>
    </DashboardLayout>
  );
}
