import { useCallApi } from '@/hooks';
import { useManageWalletContext } from '../hooks/useManageWalletContext';
import { Alert, useDataGrid } from '@/components';
import React, { useCallback, useEffect, useState } from 'react';
import { apiConfig } from '@/config/api.config';
import { toast } from 'sonner';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { RefreshCw } from 'lucide-react';
import { CurrencyProps, GroupProps, initialStateWallet, validateFormsWallet } from '../Types';

const API_URL_WALLET = apiConfig.service_wallet;
const API_URL_MASTER_DATA = apiConfig.service_master_data;

const AddDialog = () => {
  const { showAddDialog, handleAddDialog, selectedWallet } = useManageWalletContext();
  const { GetData, PostData } = useCallApi();
  const { reload } = useDataGrid();
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [formField, setFormField] = useState(initialStateWallet);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [currencies, setCurrencies] = useState<CurrencyProps[]>([]);
  const [groups, setGroups] = useState<GroupProps[]>([]);

  const resetForm = () => {
    setFormField(initialStateWallet);
    setErrors({});
  };

  const handleGroupChange = (groupId: string) => {
    setFormField((prevState) => {
      const currentGroup = prevState.group ?? [];

      const isSelected = currentGroup.includes(groupId);

      if (isSelected) {
        // Remove the group if already selected
        return {
          ...prevState,
          group: currentGroup.filter((id) => id !== groupId)
        };
      } else {
        // Add the group if not selected
        return {
          ...prevState,
          group: [...currentGroup, groupId]
        };
      }
    });
  };

  const doCreateWallet = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      setIsSubmitting(true);

      try {
        const response = await PostData(`${API_URL_MASTER_DATA}/wallet/create`, formField);

        if (response?.status) {
          handleAddDialog(false);
          toast.success('Success Create Wallet');
          reload();

          const createActivity = {
            module: 'Manage Wallet',
            description: `Create Wallet => ${formField.name}`,
            action: 'C'
          };

          doSaveLogActivity(createActivity);
        } else {
          toast.error(response?.message);
        }
      } catch (error) {
        toast.error('Something went wrong, please try again.');
      } finally {
        setIsSubmitting(false);
      }
    },
    [formField]
  );

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!validateFormsWallet(formField, setErrors, 'create')) {
      return;
    }
    console.log(formField);
    doCreateWallet(e);
  };

  const getCurrencyLists = async (sorting: any) => {
    try {
      const response = await GetData(`${API_URL_WALLET}/dashboard/currency`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
      });
      setCurrencies(response?.data.list);
    } catch (error) {
      console.error('Error fetching currency', error);
    }
  };

  const getGroupLists = async (sorting: any) => {
    try {
      const response = await GetData(`${API_URL_MASTER_DATA}/groups/list`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
      });
      setGroups(response?.data.list);
    } catch (error) {
      console.error('Error fetching group', error);
    }
  };

  const selectedGroups = groups
    .filter((g) => formField.group?.includes(g.id))
    .map((g) => g.name)
    .join(', ');

  useEffect(() => {
    getCurrencyLists([{ id: 'name', desc: false }]);
    getGroupLists([{ id: 'name', desc: false }]);
  }, []);

  useEffect(() => {
    if (showAddDialog === false) {
      resetForm();
    }
  }, [showAddDialog]);

  return (
    <Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
      <DialogContent className="container-fixed max-w-[1000px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Wallet - Create</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody className="scrollable">
          <div className="flex flex-col">
            <form onSubmit={handleSubmit}>
              <div className="card-body grid gap-5">
                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Wallet Name<span className="text-red-500">*</span>
                    </label>
                    <div className="w-full">
                      <Input
                        className={errors.name ? 'border-red-500' : ''}
                        type="text"
                        value={formField.name}
                        onChange={(e) => {
                          setFormField({ ...formField, name: e.target.value });
                          setErrors({ ...errors, name: '' });
                        }}
                        placeholder="Wallet Name"
                      />
                      {errors.name && (
                        <div className="text-red-500 text-xs mt-1">{errors.name}</div>
                      )}
                    </div>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Description<span className="text-red-500">*</span>
                    </label>
                    <div className="w-full">
                      <Input
                        className={errors.description ? 'border-red-500' : ''}
                        type="text"
                        value={formField.description}
                        onChange={(e) => {
                          setFormField({ ...formField, description: e.target.value });
                          setErrors({ ...errors, description: '' });
                        }}
                        placeholder="Description"
                      />
                      {errors.description && (
                        <div className="text-red-500 text-xs mt-1">{errors.description}</div>
                      )}
                    </div>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Status<span className="text-red-500">*</span>
                    </label>
                    <div className="w-full">
                      <Select
                        value={formField.status}
                        onValueChange={(value) => {
                          setFormField({ ...formField, status: value });
                          setErrors({ ...errors, status: '' });
                        }}
                      >
                        <SelectTrigger className={errors.status ? 'border-red-500' : ''}>
                          <SelectValue placeholder="Select Status" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="Y">Active</SelectItem>
                          <SelectItem value="N">Inactive</SelectItem>
                        </SelectContent>
                      </Select>
                      {errors.status && (
                        <div className="text-red-500 text-xs mt-1">{errors.status}</div>
                      )}
                    </div>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Currency<span className="text-red-500">*</span>
                    </label>
                    <div className="w-full">
                      <Select
                        value={formField.id_currency}
                        onValueChange={(value) => {
                          setFormField({ ...formField, id_currency: value });
                          setErrors({ ...errors, id_currency: '' });
                        }}
                      >
                        <SelectTrigger className={errors.id_currency ? 'border-red-500' : ''}>
                          <SelectValue placeholder="Select Currency Type" />
                        </SelectTrigger>
                        <SelectContent>
                          {currencies.map((currency) => (
                            <SelectItem key={currency.ID} value={currency.ID}>
                              {currency.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      {errors.id_currency && (
                        <div className="text-red-500 text-xs mt-1">{errors.id_currency}</div>
                      )}
                    </div>
                  </div>
                </div>

                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">
                      Groups<span className="text-red-500">*</span>
                    </label>
                    <div className="w-full">
                      <div className="relative w-full">
                        <Input
                          type="text"
                          placeholder="No groups selected"
                          value={selectedGroups || ''}
                          readOnly
                          className={`bg-gray-100 mb-2 ${errors.group ? 'border-red-500' : ''}`}
                        />
                        <div className="border rounded-md p-3 max-h-48 overflow-y-auto">
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                            {groups.map((group) => (
                              <div key={group.id} className="flex items-center space-x-2">
                                <Checkbox
                                  id={`group-${group.id}`}
                                  checked={formField.group?.includes(group.id)}
                                  onCheckedChange={() => handleGroupChange(group.id)}
                                />
                                <label
                                  htmlFor={`group-${group.id}`}
                                  className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                                >
                                  {group.name}
                                </label>
                              </div>
                            ))}
                          </div>
                        </div>
                        {errors.group && (
                          <div className="text-red-500 text-xs mt-1">{errors.group}</div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                <div className="flex justify-end gap-5">
                  <Button type="button" variant="outline" onClick={resetForm}>
                    Reset
                  </Button>
                  <Button variant="default" type="submit" disabled={isSubmitting}>
                    {isSubmitting ? (
                      <RefreshCw className="animate-spin h-8 w-8 text-white mx-3" />
                    ) : (
                      'Create'
                    )}
                  </Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddDialog;
