import { HydratedIsland } from '@/components/HydratedIsland';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useT } from '@/lib/i18n/react';
import { Button } from '@/components/ui/primitives/Button';
import { NumberInput } from '@/components/ui/primitives/NumberInput';
import { AdminMoneyInput } from '@/components/ui/admin/AdminMoneyInput';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/overlays/Tooltip';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useEffect } from 'react';
import { getCsrfToken } from '@/lib/csrf';

const schema = z.object({
  affiliatePct: z.number().int().min(0).max(100).optional(),
  rewardAgorot: z.number().int().min(0).optional(),
  holdDays: z.number().int().min(0).max(180).optional(),
  cookieDays: z.number().int().min(1).max(90).optional(),
  affiliateWindowDays: z.number().int().min(1).max(365).optional(),
  affiliateMaxOrders: z.number().int().min(1).max(1000).optional(),
  tier1Pct: z.number().int().min(1).max(10).optional(),
  tier2Pct: z.number().int().min(1).max(10).optional(),
  tier3Pct: z.number().int().min(1).max(10).optional(),
  tier2MinSales: z.number().int().min(1).optional(),
  tier3MinSales: z.number().int().min(1).optional(),
  referralPct: z.number().int().min(1).max(10).optional(),
});

type FormValues = z.infer<typeof schema>;

function FieldLabel({
  htmlFor,
  label,
  tooltip,
}: {
  htmlFor: string;
  label: string;
  tooltip?: string;
}) {
  if (!tooltip) {
    return (
      <label htmlFor={htmlFor} className="mb-1 block text-sm font-medium">
        {label}
      </label>
    );
  }
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <label htmlFor={htmlFor} className="mb-1 block w-fit cursor-help text-sm font-medium">
          {label}
        </label>
      </TooltipTrigger>
      <TooltipContent>{tooltip}</TooltipContent>
    </Tooltip>
  );
}

type SettingsData = {
  affiliatePct: number;
  rewardAgorot: number;
  holdDays: number;
  cookieDays: number;
  affiliateWindowDays: number;
  affiliateMaxOrders: number;
  tier1Pct: number;
  tier2Pct: number;
  tier3Pct: number;
  tier2MinSales: number;
  tier3MinSales: number;
  referralPct: number;
};

function AffiliateSettingsEditorInner() {
  const t = useT('admin_affiliates');
  const qc = useQueryClient();

  const { data } = useQuery<SettingsData>({
    queryKey: ['affiliate-settings'],
    queryFn: async () => {
      const res = await fetch('/api/admin/affiliates/settings');
      if (!res.ok) throw new Error(await res.text());
      const json = (await res.json()) as SettingsData & { ok: boolean };
      return json;
    },
  });

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
  });

  useEffect(() => {
    if (data) reset(data);
  }, [data, reset]);

  const save = useMutation({
    mutationFn: async (values: FormValues) => {
      const res = await fetch('/api/admin/affiliates/settings', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', 'x-csrf-token': getCsrfToken() },
        body: JSON.stringify(values),
      });
      if (!res.ok) throw new Error(await res.text());
      return res.json();
    },
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ['affiliate-settings'] });
    },
  });

  return (
    <TooltipProvider>
      <header className="mb-6">
        <p className="text-sm text-(--color-text-muted)">{t('settings_subtitle')}</p>
      </header>
      <form onSubmit={handleSubmit((d) => save.mutate(d))} className="max-w-md space-y-5">
        <div>
          <label htmlFor="setting-affiliatePct" className="mb-1 block text-sm font-medium">
            {t('settings_affiliate_pct')}
          </label>
          <Controller
            name="affiliatePct"
            control={control}
            render={({ field }) => (
              <NumberInput
                id="setting-affiliatePct"
                min={0}
                max={100}
                invalid={!!errors.affiliatePct}
                value={field.value ?? 0}
                onChange={(n) => field.onChange(n)}
              />
            )}
          />
          {errors.affiliatePct && (
            <p role="alert" className="mt-1 text-sm text-(--color-error)">
              {errors.affiliatePct.message}
            </p>
          )}
        </div>

        <div>
          <Controller
            name="rewardAgorot"
            control={control}
            render={({ field }) => (
              <Tooltip>
                <TooltipTrigger asChild>
                  <div>
                    <AdminMoneyInput
                      name="setting-rewardAgorot"
                      label={t('settings_reward_agorot')}
                      valueAgorot={field.value}
                      onChange={(agorot) => field.onChange(agorot)}
                    />
                  </div>
                </TooltipTrigger>
                <TooltipContent>{t('settings_reward_agorot_tooltip')}</TooltipContent>
              </Tooltip>
            )}
          />
          {errors.rewardAgorot && (
            <p role="alert" className="mt-1 text-sm text-(--color-error)">
              {errors.rewardAgorot.message}
            </p>
          )}
        </div>

        <div>
          <FieldLabel
            htmlFor="setting-holdDays"
            label={t('settings_hold_days')}
            tooltip={t('settings_hold_days_tooltip')}
          />
          <Controller
            name="holdDays"
            control={control}
            render={({ field }) => (
              <NumberInput
                id="setting-holdDays"
                min={0}
                max={180}
                invalid={!!errors.holdDays}
                value={field.value ?? 0}
                onChange={(n) => field.onChange(n)}
              />
            )}
          />
        </div>

        <div>
          <FieldLabel
            htmlFor="setting-cookieDays"
            label={t('settings_cookie_days')}
            tooltip={t('settings_cookie_days_tooltip')}
          />
          <Controller
            name="cookieDays"
            control={control}
            render={({ field }) => (
              <NumberInput
                id="setting-cookieDays"
                min={1}
                max={90}
                invalid={!!errors.cookieDays}
                value={field.value ?? 1}
                onChange={(n) => field.onChange(n)}
              />
            )}
          />
        </div>

        <div>
          <label htmlFor="setting-affiliateWindowDays" className="mb-1 block text-sm font-medium">
            {t('settings_affiliate_window_days')}
          </label>
          <Controller
            name="affiliateWindowDays"
            control={control}
            render={({ field }) => (
              <NumberInput
                id="setting-affiliateWindowDays"
                min={1}
                max={365}
                invalid={!!errors.affiliateWindowDays}
                value={field.value ?? 1}
                onChange={(n) => field.onChange(n)}
              />
            )}
          />
        </div>

        <div>
          <label htmlFor="setting-affiliateMaxOrders" className="mb-1 block text-sm font-medium">
            {t('settings_affiliate_max_orders')}
          </label>
          <Controller
            name="affiliateMaxOrders"
            control={control}
            render={({ field }) => (
              <NumberInput
                id="setting-affiliateMaxOrders"
                min={1}
                max={1000}
                invalid={!!errors.affiliateMaxOrders}
                value={field.value ?? 1}
                onChange={(n) => field.onChange(n)}
              />
            )}
          />
        </div>

        {/* Tier section */}
        <div className="border-t border-(--color-border) pt-5">
          <Tooltip>
            <TooltipTrigger asChild>
              <h2 className="mb-2 w-fit cursor-help text-base font-semibold text-(--color-text)">
                {t('settings_tiers_heading')}
              </h2>
            </TooltipTrigger>
            <TooltipContent>{t('settings_tiers_heading_tooltip')}</TooltipContent>
          </Tooltip>
          <p className="mb-4 text-xs text-(--color-text-muted)">
            {t('settings_tier_ladder_summary')}
          </p>
          <div className="space-y-4">
            <div>
              <label htmlFor="setting-tier1Pct" className="mb-1 block text-sm font-medium">
                {t('settings_tier1_pct')}
              </label>
              <Controller
                name="tier1Pct"
                control={control}
                render={({ field }) => (
                  <NumberInput
                    id="setting-tier1Pct"
                    min={1}
                    max={10}
                    value={field.value ?? 1}
                    onChange={(n) => field.onChange(n)}
                  />
                )}
              />
            </div>
            <div>
              <label htmlFor="setting-tier2Pct" className="mb-1 block text-sm font-medium">
                {t('settings_tier2_pct')}
              </label>
              <Controller
                name="tier2Pct"
                control={control}
                render={({ field }) => (
                  <NumberInput
                    id="setting-tier2Pct"
                    min={1}
                    max={10}
                    value={field.value ?? 1}
                    onChange={(n) => field.onChange(n)}
                  />
                )}
              />
            </div>
            <div>
              <FieldLabel
                htmlFor="setting-tier2MinSales"
                label={t('settings_tier2_min_sales')}
                tooltip={t('settings_tier2_min_sales_tooltip')}
              />
              <Controller
                name="tier2MinSales"
                control={control}
                render={({ field }) => (
                  <NumberInput
                    id="setting-tier2MinSales"
                    min={1}
                    value={field.value ?? 1}
                    onChange={(n) => field.onChange(n)}
                  />
                )}
              />
            </div>
            <div>
              <label htmlFor="setting-tier3Pct" className="mb-1 block text-sm font-medium">
                {t('settings_tier3_pct')}
              </label>
              <Controller
                name="tier3Pct"
                control={control}
                render={({ field }) => (
                  <NumberInput
                    id="setting-tier3Pct"
                    min={1}
                    max={10}
                    value={field.value ?? 1}
                    onChange={(n) => field.onChange(n)}
                  />
                )}
              />
            </div>
            <div>
              <FieldLabel
                htmlFor="setting-tier3MinSales"
                label={t('settings_tier3_min_sales')}
                tooltip={t('settings_tier3_min_sales_tooltip')}
              />
              <Controller
                name="tier3MinSales"
                control={control}
                render={({ field }) => (
                  <NumberInput
                    id="setting-tier3MinSales"
                    min={1}
                    value={field.value ?? 1}
                    onChange={(n) => field.onChange(n)}
                  />
                )}
              />
            </div>
          </div>
        </div>

        {/* Referral section */}
        <div className="border-t border-(--color-border) pt-5">
          <h2 className="mb-4 text-base font-semibold text-(--color-text)">
            {t('settings_referral_heading')}
          </h2>
          <div>
            <FieldLabel
              htmlFor="setting-referralPct"
              label={t('settings_referral_pct')}
              tooltip={t('settings_referral_pct_tooltip')}
            />
            <Controller
              name="referralPct"
              control={control}
              render={({ field }) => (
                <NumberInput
                  id="setting-referralPct"
                  min={1}
                  max={10}
                  value={field.value ?? 1}
                  onChange={(n) => field.onChange(n)}
                />
              )}
            />
          </div>
        </div>

        <Button type="submit" variant="primary" size="md" loading={save.isPending}>
          {t('settings_save')}
        </Button>

        {save.isSuccess && (
          <p role="status" className="text-sm text-(--color-success)">
            {t('settings_saved')}
          </p>
        )}
        {save.isError && (
          <p role="alert" className="mt-2 text-sm text-(--color-error)">
            {String(save.error)}
          </p>
        )}
      </form>
    </TooltipProvider>
  );
}

export function AffiliateSettingsEditor() {
  return (
    <HydratedIsland>
      <AffiliateSettingsEditorInner />
    </HydratedIsland>
  );
}
