import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { handleApiError } from '@/lib/error-handler';
import { request } from '@/lib/fetcher';
import { MinusCircleIcon, PlusCircleIcon } from '@phosphor-icons/react';
import { useState, useTransition } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

type Wallet = 'main' | 'interest';
type ActionType = 'add' | 'remove';

export default function AdjustBalance({
  userId,
  wallet,
  mutate,
}: {
  userId: string;
  wallet: Wallet;
  mutate: () => void;
}) {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const [action, setAction] = useState<ActionType>('add');
  const [amount, setAmount] = useState('');
  const [isPending, startTransition] = useTransition();

  const walletLabel = wallet === 'main' ? t('Main Wallet') : t('Profit Wallet');

  const handleSubmit = () => {
    const parsed = parseFloat(amount);
    if (!parsed || parsed <= 0) {
      toast.error(t('Enter a valid amount greater than 0'));
      return;
    }

    startTransition(async () => {
      try {
        const res = await request.post(
          `/api/admin/users/${userId}/adjust-balance`,
          {
            type: action,
            wallet,
            amount: parsed,
          },
        );
        if (res.data?.success) {
          toast.success(res.data.message);
          setAmount('');
          setOpen(false);
          mutate();
        }
      } catch (err) {
        handleApiError(err);
      }
    });
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <button className="cursor-pointer rounded-lg p-1 text-black/30 transition-colors hover:bg-black/5 hover:text-black/60">
          <PlusCircleIcon weight="bold" className="size-5" />
        </button>
      </DialogTrigger>

      <DialogContent className="max-w-sm">
        <DialogHeader>
          <DialogTitle>
            {t('Adjust')} {walletLabel}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <div className="grid grid-cols-2 gap-2">
            <button
              type="button"
              onClick={() => setAction('add')}
              className={`flex items-center justify-center gap-2 rounded-xl border py-2.5 text-sm font-medium transition-colors ${
                action === 'add'
                  ? 'border-success/40 bg-success/10 text-success'
                  : 'border-black/10 text-black/40 hover:border-black/20 hover:text-black/60'
              }`}
            >
              <PlusCircleIcon weight="bold" className="size-4" />
              {t('Add')}
            </button>
            <button
              type="button"
              onClick={() => setAction('remove')}
              className={`flex items-center justify-center gap-2 rounded-xl border py-2.5 text-sm font-medium transition-colors ${
                action === 'remove'
                  ? 'border-destructive/40 bg-destructive/10 text-destructive'
                  : 'border-black/10 text-black/40 hover:border-black/20 hover:text-black/60'
              }`}
            >
              <MinusCircleIcon weight="bold" className="size-4" />
              {t('Remove')}
            </button>
          </div>

          <div className="space-y-1.5">
            <Label>{t('Amount')}</Label>
            <div className="relative">
              <span className="absolute top-1/2 left-3 -translate-y-1/2 text-sm text-black/40">
                $
              </span>
              <Input
                type="number"
                min="0.01"
                step="0.01"
                placeholder="0.00"
                value={amount}
                onChange={(e) => setAmount(e.target.value)}
                className="pl-7"
              />
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => setOpen(false)}
            disabled={isPending}
          >
            {t('Cancel')}
          </Button>
          <Button
            onClick={handleSubmit}
            loading={isPending}
            disabled={isPending || !amount}
            className={
              action === 'remove'
                ? 'border-destructive bg-destructive text-white hover:bg-destructive/90'
                : ''
            }
          >
            {action === 'add' ? t('Add Balance') : t('Remove Balance')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
