'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import {
  addUsers,
  fetchUserById,
  updateUsers,
} from '@/network/apis/dashboard/userManagment/users/users.apis';
import { getCountries } from '@/network/apis/shared/countries/countries';
import { CountryProps } from '@/network/apis/shared/countries/type';
import usePackagesList from '@/modules/client-management/hooks/usePackagesList';
import { zodResolver } from '@hookform/resolvers/zod';
import { RiCheckboxCircleFill, RiErrorWarningFill } from '@remixicon/react';
import { useMutation, useQuery } 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 {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinners';
import { Switch } from '@/components/ui/switch';
import { UserAddSchema, UserAddSchemaType } from './user-client-add-schema';

type BalanceKey = Extract<
  keyof UserAddSchemaType,
  | 'requests_balance'
  | 'search_balance'
  | 'social_listening_balance'
  | 'lookalike_balance'
  | 'mynetwork_balance'
  | 'campaign_balance'
  | 'competitor_analysis_balance'
  | 'phone_number_balance'
  | 'media_plan_balance'
  | 'media_plan_creators_balance'
  | 'whatsapp_message_balance'
  | 'collaboration_request_balance'
  | 'relationship_lists_limit'
  | 'influencers_per_list_limit'
  | 'credit'
>;

const BALANCE_FIELDS: { name: BalanceKey; label: string; hint?: string }[] = [
  { name: 'requests_balance', label: 'Reports Balance' },
  { name: 'search_balance', label: 'Search Balance' },
  { name: 'social_listening_balance', label: 'Social Listening Balance' },
  { name: 'lookalike_balance', label: 'Lookalike Balance' },
  { name: 'mynetwork_balance', label: 'My Network Balance' },
  { name: 'campaign_balance', label: 'Campaign Balance' },
  { name: 'competitor_analysis_balance', label: 'Competitor Analysis Balance' },
  { name: 'phone_number_balance', label: 'Phone Number Balance' },
  { name: 'media_plan_balance', label: 'Media Plan Balance' },
  { name: 'media_plan_creators_balance', label: 'Media Plan Creators Balance' },
  { name: 'whatsapp_message_balance', label: 'WhatsApp Message Balance' },
  { name: 'collaboration_request_balance', label: 'Collaboration Request Balance' },
  { name: 'relationship_lists_limit', label: 'Relationship Lists Limit', hint: '0 = unlimited' },
  { name: 'influencers_per_list_limit', label: 'Influencers / List Limit', hint: '0 = unlimited' },
  { name: 'credit', label: 'Credit' },
];

const UserAdd = () => {
  const router = useRouter();
  const params = useParams();
  const id = params?.slug?.[0] ? Number(params?.slug?.[0]) : undefined;
  const isEdit = !!id;

  const [packageSearch, setPackageSearch] = useState('');

  const ACCOUNT_TYPES = [
    { label: 'Admin', value: 1 },
    { label: 'Brand', value: 2 },
    { label: 'Influencer', value: 3 },
  ];

  const { data: countries } = useQuery({
    queryKey: ['countries'],
    queryFn: getCountries,
    enabled: true,
    select: (data) => data?.data,
  });

  const { data: packages } = usePackagesList(packageSearch || undefined);

  const { data: userDetails } = useQuery({
    queryKey: ['user_details', id],
    queryFn: async () => {
      if (id === undefined) return;
      const response = await fetchUserById(id?.toString());
      return response;
    },
    enabled: isEdit,
  });

  const form = useForm<UserAddSchemaType>({
    resolver: zodResolver(UserAddSchema),
    defaultValues: {
      first_name: '',
      last_name: '',
      brand_name: '',
      phone: '',
      country_id: undefined as unknown as number,
      account_type_id: 2,
      email: '',
      password: undefined,
      password_confirmation: undefined,
      is_activated: 1,
      package_id: undefined,
      requests_balance: undefined,
      search_balance: undefined,
      social_listening_balance: undefined,
      lookalike_balance: undefined,
      mynetwork_balance: undefined,
      campaign_balance: undefined,
      competitor_analysis_balance: undefined,
      phone_number_balance: undefined,
      media_plan_balance: undefined,
      media_plan_creators_balance: undefined,
      whatsapp_message_balance: undefined,
      collaboration_request_balance: undefined,
      relationship_lists_limit: undefined,
      influencers_per_list_limit: undefined,
      credit: undefined,
    },
    mode: 'onSubmit',
  });

  useEffect(() => {
    if (userDetails && Object.keys(userDetails).length) {
      form.reset({
        first_name: userDetails.first_name ?? '',
        last_name: userDetails.last_name ?? '',
        brand_name: userDetails.brand_name ?? '',
        phone: userDetails.phone ?? '',
        country_id: Number(userDetails.country?.id ?? 0),
        account_type_id: Number(userDetails.account_type_id ?? 0),
        email: userDetails.email ?? '',
        password: undefined,
        password_confirmation: undefined,
        is_activated: userDetails.is_activated ? 1 : 0,
        package_id: undefined,
        requests_balance: userDetails.requests_balance ?? undefined,
        search_balance: userDetails.search_balance ?? undefined,
        social_listening_balance: userDetails.social_listening_balance ?? undefined,
        lookalike_balance: userDetails.lookalike_balance ?? undefined,
        mynetwork_balance: userDetails.mynetwork_balance ?? undefined,
        campaign_balance: userDetails.campaign_balance ?? undefined,
        competitor_analysis_balance: userDetails.competitor_analysis_balance ?? undefined,
        phone_number_balance: userDetails.phone_number_balance ?? undefined,
        media_plan_balance: userDetails.media_plan_balance ?? undefined,
        media_plan_creators_balance: userDetails.media_plan_creators_balance ?? undefined,
        whatsapp_message_balance: userDetails.whatsapp_message_balance ?? undefined,
        collaboration_request_balance: userDetails.collaboration_request_balance ?? undefined,
        relationship_lists_limit: userDetails.relationship_lists_limit ?? undefined,
        influencers_per_list_limit: userDetails.influencers_per_list_limit ?? undefined,
        credit: userDetails.credit ?? undefined,
      });
    }
  }, [userDetails, form]);

  const mutation = useMutation({
    mutationFn: async (values: UserAddSchemaType) => {
      const fd = new FormData();
      fd.append('first_name', values.first_name);
      fd.append('last_name', values.last_name);
      fd.append('brand_name', values?.brand_name ?? '');
      fd.append('phone', values.phone);
      fd.append('country_id', String(values.country_id));
      fd.append('account_type_id', String(values.account_type_id));
      fd.append('email', values.email);
      if (values.password) fd.append('password', values.password);
      if (values.password_confirmation) {
        fd.append('password_confirmation', values.password_confirmation);
      }
      fd.append('is_activated', String(values.is_activated));

      if (values.package_id) fd.append('package_id', String(values.package_id));
      BALANCE_FIELDS.forEach(({ name }) => {
        fd.append(name, String(values[name] ?? 0));
      });

      if (isEdit) {
        await updateUsers(fd, id?.toString());
      } else {
        await addUsers(fd);
      }
    },
    onSuccess: () => {
      const message = isEdit
        ? 'User updated successfully'
        : 'User added successfully';
      toast.custom(
        () => (
          <Alert variant="mono" icon="success" close={false}>
            <AlertIcon>
              <RiCheckboxCircleFill />
            </AlertIcon>
            <AlertTitle>{message}</AlertTitle>
          </Alert>
        ),
        { position: 'top-center' },
      );
      router.push('/client-management');
    },
    onError: (error: unknown) => {
      const axiosErr = error as { response?: { data?: { message?: string; errors?: Record<string, string[]> }; status?: number } };
      const apiErrors = axiosErr?.response?.data?.errors;
      const apiMessage = axiosErr?.response?.data?.message;

      let errorMessage = (error as Error).message || 'An error occurred';
      if (apiErrors) {
        const allMessages = Object.values(apiErrors).flat();
        errorMessage = allMessages.join(', ');
      } else if (apiMessage) {
        errorMessage = apiMessage;
      }

      if (apiErrors) {
        const fieldMap: Record<string, keyof UserAddSchemaType> = {
          first_name: 'first_name', last_name: 'last_name', email: 'email',
          phone: 'phone', password: 'password', password_confirmation: 'password_confirmation',
          country_id: 'country_id', account_type_id: 'account_type_id', brand_name: 'brand_name',
        };
        Object.entries(apiErrors).forEach(([field, messages]) => {
          const formField = fieldMap[field];
          if (formField) {
            form.setError(formField, { type: 'server', message: messages[0] });
          }
        });
      }

      toast.custom(
        () => (
          <Alert variant="mono" icon="destructive" close={false}>
            <AlertIcon>
              <RiErrorWarningFill />
            </AlertIcon>
            <AlertTitle>{errorMessage}</AlertTitle>
          </Alert>
        ),
        { position: 'top-center' },
      );
    },
  });

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

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

  return (
    <div className="p-10">
      <Form {...form}>
        <form className="w-full" onSubmit={form.handleSubmit(handleSubmit)}>
          <div className="flex justify-between mb-5">
            <p className="font-bold text-2xl">
              {isEdit ? 'Update Client User' : 'Create Client User'}
            </p>
            <div className="flex">
              <FormField
                control={form.control}
                name="is_activated"
                render={({ field }) => (
                  <FormItem className="flex items-center space-x-2">
                    <FormLabel htmlFor="is_activated">Status</FormLabel>
                    <FormControl>
                      <Switch
                        id="is_activated"
                        checked={field.value === 1}
                        onCheckedChange={(checked) =>
                          field.onChange(checked ? 1 : 0)
                        }
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </div>

          <div className="w-full flex items-center gap-2 mb-5">
            <FormField
              control={form.control}
              name="first_name"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>First Name</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter first name" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="last_name"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Last Name</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter last name" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          <div className="w-full flex items-center gap-2 mb-5">
            <FormField
              control={form.control}
              name="country_id"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Country</FormLabel>
                  <FormControl>
                    <Select
                      onValueChange={(value) => field.onChange(Number(value))}
                      value={field.value ? field.value.toString() : ''}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Country" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectGroup>
                          {countries?.data?.map((country: CountryProps) => (
                            <SelectItem
                              key={country.id}
                              value={`${country.id}`}
                            >
                              {country.name}
                            </SelectItem>
                          ))}
                        </SelectGroup>
                      </SelectContent>
                    </Select>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="phone"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Phone</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter phone" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          <div className="w-full flex items-center gap-2 mb-5">
            <FormField
              control={form.control}
              name="account_type_id"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Account Type</FormLabel>
                  <FormControl>
                    <Select
                      onValueChange={(val) => field.onChange(Number(val))}
                      value={field.value ? String(field.value) : ''}
                      disabled
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select account type" />
                      </SelectTrigger>
                      <SelectContent>
                        {ACCOUNT_TYPES.map((opt) => (
                          <SelectItem key={opt.value} value={String(opt.value)}>
                            {opt.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            {form.watch('account_type_id') === 2 && (
              <FormField
                control={form.control}
                name="brand_name"
                render={({ field }) => (
                  <FormItem className="w-full">
                    <FormLabel>Brand Name</FormLabel>
                    <FormControl>
                      <Input placeholder="Enter brand name" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}
          </div>

          <div className="w-full flex items-center gap-2 mb-5">
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Email</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter email" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Password {isEdit ? '(optional)' : ''}</FormLabel>
                  <FormControl>
                    <Input
                      type="password"
                      placeholder="Enter password"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          <div className="w-full flex items-center gap-2 mb-5">
            <FormField
              control={form.control}
              name="password_confirmation"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>
                    Confirm Password {isEdit ? '(optional)' : ''}
                  </FormLabel>
                  <FormControl>
                    <Input
                      type="password"
                      placeholder="Confirm password"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <div className="w-full" />
          </div>

          {/* Package */}
          <div className="w-full flex items-center gap-2 mb-5">
            <FormField
              control={form.control}
              name="package_id"
              render={({ field }) => (
                <FormItem className="w-full">
                  <FormLabel>Package</FormLabel>
                  <FormControl>
                    <Select
                      onValueChange={(value) => field.onChange(Number(value))}
                      value={field.value ? String(field.value) : ''}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select package" />
                      </SelectTrigger>
                      <SelectContent>
                        <div className="p-2">
                          <Input
                            placeholder="Search packages..."
                            value={packageSearch}
                            onChange={(e) => setPackageSearch(e.target.value)}
                            onClick={(e) => e.stopPropagation()}
                            onKeyDown={(e) => e.stopPropagation()}
                          />
                        </div>
                        <SelectGroup>
                          {packages?.map((pkg) => (
                            <SelectItem key={pkg.id} value={String(pkg.id)}>
                              {pkg.name}
                            </SelectItem>
                          ))}
                        </SelectGroup>
                      </SelectContent>
                    </Select>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <div className="w-full" />
          </div>

          {/* Balances */}
          <div className="mb-3">
            <p className="font-semibold text-lg">Balances &amp; limits</p>
            <p className="text-sm text-muted-foreground">
              Set the initial balance for each feature. Limits where <span className="font-medium">0 = unlimited</span> are noted.
            </p>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-2 gap-y-3 mb-5">
            {BALANCE_FIELDS.map((bf) => (
              <FormField
                key={bf.name}
                control={form.control}
                name={bf.name}
                render={({ field }) => (
                  <FormItem className="w-full">
                    <FormLabel>
                      {bf.label}
                      {bf.hint ? <span className="ml-1 text-xs text-muted-foreground">({bf.hint})</span> : null}
                    </FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min={0}
                        placeholder="0"
                        {...field}
                        value={field.value ?? ''}
                        onChange={(e) =>
                          field.onChange(
                            e.target.value === '' ? undefined : Number(e.target.value),
                          )
                        }
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            ))}
          </div>

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

export default UserAdd;
