﻿import PageHeading from '@/components/common/page-heading';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import { createRequest } from '@/data/request/create-request';
import { useCurrency } from '@/hooks/use-currency';
import { useWithdrawStore } from '@/store/useWithdrawStore';
import { SharedData } from '@/types';
import { getImageUrl } from '@/utils/getImageUrl';
import { calculateFees, formatFee } from '@/utils/handleFee';
import { zodResolver } from '@hookform/resolvers/zod';
import { router, usePage } from '@inertiajs/react';
import {
  ArrowCounterClockwiseIcon,
  CaretLeftIcon,
  CaretRightIcon,
  InfoIcon,
  WarningIcon,
} from '@phosphor-icons/react';
import { useTransition } from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import z from 'zod';

const WithdrawConfirmSchema = z.object({
  amount: z.coerce.number().min(1, 'Amount is required'),
  details: z.any().optional(),
});

type TWithdrawConfirmSchema = z.infer<typeof WithdrawConfirmSchema>;

const WithdrawConfirm = () => {
  const { t } = useTranslation();
  const [isPending, startTransition] = useTransition();
  const { gateway } = useWithdrawStore();
  const { branding } = usePage<SharedData>().props;

  const form = useForm({
    resolver: zodResolver(WithdrawConfirmSchema),
    defaultValues: { amount: '', details: {} },
  });

  // eslint-disable-next-line react-hooks/incompatible-library
  const amount = form.watch('amount');
  const numericAmount = Number(amount || 0);
  const fee = gateway ? calculateFees(numericAmount, gateway) : null;

  const payoutAmount =
    numericAmount > 0 ? numericAmount / (gateway?.exchange_rate ?? 1) : 0;

  const handleSubmit = (values: TWithdrawConfirmSchema) => {
    const min = gateway?.min_amount ?? 0;
    const max = gateway?.max_amount ?? Infinity;

    if (gateway && (values.amount < min || values.amount > max)) {
      form.setError('amount', {
        message: `Amount must be between ${min.toLocaleString()} and ${max.toLocaleString()}`,
      });
      return;
    }

    startTransition(async () => {
      const isManual = gateway?.gateway_type === 'manual';

      const formData = isManual
        ? {
            manual_method_id: gateway?.id,
            amount: values.amount,
            details: values.details ?? {},
          }
        : {
            auto_method_id: gateway?.id,
            amount: values.amount,
            recipient_details: values.details ?? {},
          };

      const url = isManual
        ? '/api/user/withdrawals/manual'
        : '/api/user/withdrawals/auto';

      const res = await createRequest({ url, formData });

      if (res?.transaction_id) {
        toast.success(res?.message);
        router.visit('/withdraw/success');
      }
    });
  };

  const recipientFields =
    gateway?.gateway_type === 'auto'
      ? (gateway?.withdraw_fields ?? [])
      : (gateway?.fields ?? []);

  return (
    <>
      <PageHeading
        variant="default"
        title={t('Confirm Withdrawal')}
        description={t('Review and confirm your withdrawal details.')}
      />

      <Card>
        <h3 className="py-4 text-center text-2xl font-medium">
          {t('Confirm Withdrawal')}
        </h3>
        <Separator className="my-4 bg-black/5 dark:bg-white/5" />

        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)}>
            {gateway === null ? (
              <div className="flex flex-col items-center py-10 text-center text-muted-foreground">
                <WarningIcon
                  weight="duotone"
                  className="mb-2 size-10 text-foreground dark:text-white/60"
                />
                <p className="mb-4">{t('No withdrawal method selected.')}</p>
                <Button
                  type="button"
                  variant="secondary"
                  onClick={() => router.visit('/withdraw')}
                  className="min-w-48 rounded-full"
                >
                  <ArrowCounterClockwiseIcon weight="bold" />
                  <span>{t('Select Method')}</span>
                </Button>
              </div>
            ) : (
              <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
                <div className="space-y-4">
                  <div className="flex items-center gap-3 rounded-2xl border border-black/5 bg-white/10 p-4 dark:border-white/10">
                    <img
                      src={getImageUrl(gateway.logo)}
                      alt={gateway.name}
                      className="size-12 object-contain"
                    />
                    <div>
                      <p className="font-medium">{gateway.name}</p>
                      <p className="text-sm text-black/50 dark:text-white/50">
                        {gateway.currency}
                      </p>
                    </div>
                  </div>

                  {gateway.instructions && (
                    <div className="rounded-2xl border border-black/5 bg-white/10 px-4 py-2.5 dark:border-white/10">
                      <div className="mb-2 flex items-center gap-2">
                        <InfoIcon
                          weight="fill"
                          className="size-5 text-black/70 dark:text-white/50"
                        />
                        <p>{t('Instructions')}</p>
                      </div>
                      <p className="text-sm text-black/70 opacity-50 dark:text-white/50">
                        {gateway.instructions}
                      </p>
                    </div>
                  )}

                  <FormField
                    control={form.control}
                    name="amount"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="flex justify-between px-4 font-lexend text-black/70 dark:text-white/50">
                          <span>{t('Withdrawal Amount')}</span>
                          <span>
                            {gateway.min_amount != null &&
                              gateway.max_amount != null &&
                              `${t('Limit:')} ${gateway.min_amount.toLocaleString()}-${gateway.max_amount.toLocaleString()}`}
                          </span>
                        </FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            inputMode="decimal"
                            placeholder={t('Enter withdrawal amount')}
                            className="rounded-xl border border-black/5 bg-black/5 dark:border-white/5 dark:bg-secondary"
                            {...field}
                            value={field.value as string | number}
                          />
                        </FormControl>
                        <FormMessage className="px-4" />
                      </FormItem>
                    )}
                  />

                  {recipientFields.map((f) => (
                    <FormField
                      key={f.name}
                      control={form.control}
                      name={`details.${f.name}`}
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="flex justify-between px-4 font-lexend text-black/70 capitalize dark:text-white/50">
                            {f.label}
                          </FormLabel>
                          <FormControl>
                            <Input
                              type={f.type}
                              inputMode={
                                f.type === 'number' ? 'numeric' : 'text'
                              }
                              placeholder={f.placeholder}
                              className="rounded-xl border border-black/5 bg-black/5 dark:border-white/5 dark:bg-secondary"
                              {...field}
                              value={field.value as string | number}
                            />
                          </FormControl>
                          <FormMessage className="px-4" />
                        </FormItem>
                      )}
                    />
                  ))}
                </div>

                <div className="space-y-4 font-lexend">
                  <div className="flex items-center justify-between border-b border-dashed border-white/15">
                    <p>{t('Method')}</p>
                    <p>{gateway.name}</p>
                  </div>
                  <div className="flex items-center justify-between border-b border-dashed border-white/15">
                    <p>{t('Processing')}</p>
                    <p>
                      {gateway.gateway_type === 'auto'
                        ? t('Automatic')
                        : t('Manual')}
                    </p>
                  </div>
                  <div className="flex items-center justify-between border-b border-dashed border-white/15">
                    <p>{t('Fee')}</p>
                    <p>
                      {formatFee({
                        fixed_charge: gateway.fixed_charge,
                        percent_charge: gateway.percent_charge,
                        currency: branding?.branding?.site_currency,
                      })}
                    </p>
                  </div>
                  <div className="flex items-center justify-between border-b border-dashed border-white/15">
                    <p>{t('Withdrawal Amount')}</p>
                    <p>
                      <Money
                        value={numericAmount}
                        currency={branding?.branding?.site_currency}
                      />
                    </p>
                  </div>
                  <div className="flex items-center justify-between border-b border-dashed border-white/15">
                    <p>{t('Fee')}</p>
                    <p>
                      <span className="text-2xl font-medium">-</span>
                      <Money
                        value={fee?.totalFee}
                        currency={branding?.branding?.site_currency}
                      />
                    </p>
                  </div>
                  <div className="flex items-center justify-between border-b border-dashed border-white/15">
                    <p>{t('Total Deducted')}</p>
                    <p>
                      <Money
                        value={fee?.total}
                        currency={branding?.branding?.site_currency}
                      />
                    </p>
                  </div>
                  {gateway.exchange_rate && gateway.exchange_rate !== 1 && (
                    <div className="flex items-center justify-between border-b border-dashed border-white/15">
                      <p>{t('You Receive')}</p>
                      <p>
                        <Money
                          value={payoutAmount}
                          currency={gateway.currency}
                        />
                      </p>
                    </div>
                  )}
                </div>
              </div>
            )}

            <Separator className="my-4 bg-black/5 dark:bg-white/5" />

            <div className="flex justify-between">
              <Button
                type="button"
                variant="secondary"
                onClick={() => router.visit('/withdraw')}
                className="min-w-32"
              >
                <CaretLeftIcon weight="bold" />
                <span>{t('Back')}</span>
              </Button>
              <Button
                type="submit"
                loading={isPending}
                variant="primary"
                className="min-w-32"
                disabled={gateway === null}
              >
                <span>{t('Submit')}</span>
                <CaretRightIcon weight="bold" />
              </Button>
            </div>
          </form>
        </Form>
      </Card>
    </>
  );
};

const Money = ({ value, currency }: { value?: number; currency?: string }) => {
  const { format } = useCurrency();
  const amount = format(value || 0, 'symbol', currency);
  const splitAmount = amount.includes('.') ? amount.split('.') : [amount, '00'];
  const [intPart, decPart] = splitAmount;

  return (
    <span className="font-lexend">
      <span className="text-2xl font-medium tabular-nums">{intPart}</span>
      <span className="tabular-nums">.{decPart}</span>
      <span className="ml-1 text-sm opacity-80">{currency}</span>
    </span>
  );
};

WithdrawConfirm.title = 'Withdraw Confirm';

export default WithdrawConfirm;
