'use client';

import { useRouter } from 'next/navigation';
import { createPayout } from '@/network/apis/dashboard/payouts/payouts.apis';
import { zodResolver } from '@hookform/resolvers/zod';
import { RiCheckboxCircleFill, RiErrorWarningFill } from '@remixicon/react';
import { useMutation } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { Alert, AlertIcon, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinners';
import { PayoutAddSchema, PayoutAddSchemaType } from './payout-add-schema';

export default function PayoutAdd() {
  const router = useRouter();

  const form = useForm<PayoutAddSchemaType>({
    resolver: zodResolver(PayoutAddSchema),
    defaultValues: {
      amount: 0,
      purpose: '',
      destination_type: 'bank',
      destination_iban: '',
      destination_name: '',
      destination_mobile: '',
      destination_country: '',
      destination_city: '',
      comment: '',
    },
    mode: 'onSubmit',
  });

  const mutation = useMutation({
    mutationFn: async (values: PayoutAddSchemaType) => {
      const payload = {
        amount: values.amount,
        purpose: values.purpose,
        comment: values.comment || null,
        destination: {
          type: values.destination_type,
          iban: values.destination_iban || undefined,
          name: values.destination_name,
          mobile: values.destination_mobile || undefined,
          country: values.destination_country,
          city: values.destination_city,
        },
      };
      await createPayout(payload);
    },
    onSuccess: () => {
      const message = 'Payout created successfully';
      toast.custom(
        () => (
          <Alert variant="mono" icon="success" close={false}>
            <AlertIcon>
              <RiCheckboxCircleFill />
            </AlertIcon>
            <AlertTitle>{message}</AlertTitle>
          </Alert>
        ),
        { position: 'top-center' },
      );
      router.push('/payout'); // غيّرها إلى مسارك الفعلي لقائمة الـ payouts
    },
    onError: (error: Error) => {
      toast.custom(
        () => (
          <Alert variant="mono" icon="destructive" close={false}>
            <AlertIcon>
              <RiErrorWarningFill />
            </AlertIcon>
            <AlertTitle>{error.message}</AlertTitle>
          </Alert>
        ),
        { position: 'top-center' },
      );
    },
  });

  const isProcessing = mutation.status === 'pending';

  const handleSubmit = (values: PayoutAddSchemaType) => {
    mutation.mutate(values);
  };

  return (
    <div className="p-10">
      <Form {...form}>
        <form
          className="w-full space-y-6"
          onSubmit={form.handleSubmit(handleSubmit)}
        >
          <div className="flex justify-between mb-5">
            <p className="font-bold text-2xl">{'Create Payout'}</p>
          </div>

          {/* Amount + Purpose */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField
              control={form.control}
              name="amount"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Amount</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      step="0.01"
                      min="0"
                      placeholder="Enter amount"
                      {...field}
                      onChange={(e) => field.onChange(Number(e.target.value))}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="purpose"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Purpose</FormLabel>
                  <FormControl>
                    <Input placeholder="e.g. bills_or_rent" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          {/* Destination */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField
              control={form.control}
              name="destination_type"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Destination Type</FormLabel>
                  <FormControl>
                    <Input placeholder="bank / wallet / card" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="destination_iban"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Destination IBAN</FormLabel>
                  <FormControl>
                    <Input placeholder="Required if type is bank" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="destination_name"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Beneficiary Name</FormLabel>
                  <FormControl>
                    <Input placeholder="Full name" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="destination_mobile"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Beneficiary Mobile</FormLabel>
                  <FormControl>
                    <Input placeholder="05xxxxxxxx" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="destination_country"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Country</FormLabel>
                  <FormControl>
                    <Input placeholder="Saudi Arabia" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="destination_city"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>City</FormLabel>
                  <FormControl>
                    <Input placeholder="Riyadh" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          {/* Optional comment */}
          <FormField
            control={form.control}
            name="comment"
            render={({ field }) => (
              <FormItem className="w-full">
                <FormLabel>Comment (optional)</FormLabel>
                <FormControl>
                  <Input placeholder="Any note..." {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <div className="flex justify-end">
            <Button
              type="button"
              variant="outline"
              className="mx-3"
              onClick={() => router.push('/payout')}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isProcessing}>
              {isProcessing && <Spinner className="animate-spin" />}
              {'Add'}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
}
