import { Alert, useDataGrid } from '@/components';
import { useManageWalletContext } from '../hooks/useManageWalletContext';
import { useCallApi } from '@/hooks';
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 { 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 EditDialog = () => {
  const { showEditDialog, handleEditDialog, selectedWallet } = useManageWalletContext();
  const { reload } = useDataGrid();
  const { GetData, PutData } = useCallApi();
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [formField, setFormField] = useState(initialStateWallet);
  const [currencies, setCurrencies] = useState<CurrencyProps[]>([]);
  const [groups, setGroups] = useState<GroupProps[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

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

  const doUpdateWallet = useCallback(
    async (payload: { name: string; description: string; status: string }) => {
      // e.preventDefault();
      setIsSubmitting(true);

      try {
        const response = await PutData(
          `${API_URL_MASTER_DATA}/wallet/update/${selectedWallet?.id}`,
          payload
        );

        if (response?.status) {
          handleEditDialog(false, null);
          toast.success('Success Update Wallet');
          reload();

          const createActivity = {
            module: 'Manage Wallet',
            description: `Edit Wallet => ${selectedWallet?.id} - ${selectedWallet?.name}`,
            action: 'U'
          };

          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();

    // const { name, description, status } = formField;
    const payload = {
      name: formField.name,
      description: formField.description,
      status: formField.status
    };

    if (!validateFormsWallet(payload, setErrors, 'update')) {
      return;
    }
    doUpdateWallet(payload);
  };

  const doFetchData = useCallback(async (id: string) => {
    setIsLoading(true);
    const minDelay = new Promise((resolve) => setTimeout(resolve, 300));
    const fetchData = GetData(`${API_URL_MASTER_DATA}/wallet/detail/${id}`, {
      id
    });
    const [response] = await Promise.all([fetchData, minDelay]);

    if (response?.status) {
      setFormField((prev) => ({
        ...prev,
        name: response?.data.name,
        description: response?.data.description,
        status: response?.data.status,
        currency_id: response?.data.id_currency,
        group: Array.isArray(response?.data.group)
          ? response?.data.group.map((target: GroupProps) => target.id)
          : []
      }));
    }
    setIsLoading(false);
  }, []);

  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'
      });
      // console.log('Currency: ', response?.data);
      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'
      });
      // console.log('Group: ', response?.data);
      setGroups(response?.data.list);
    } catch (error) {
      console.error('Error fetching group', error);
    }
  };

  const selectedCurrency = currencies.find((currency) => currency.ID === formField.id_currency);

  const selectedGroupNames = 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 (selectedWallet) {
      doFetchData(selectedWallet?.id);
    }
  }, [selectedWallet]);

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

  return (
    <Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Wallet - Update</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody className="scrollable">
          <div className="flex flex-col">
            {isLoading ? (
              <div className="flex flex-col items-center justify-center p-8">
                <div className="animate-pulse flex space-x-4 w-full">
                  <div className="flex-1 space-y-4 py-1">
                    <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                    <div className="space-y-2">
                      <div className="h-4 bg-gray-200 rounded"></div>
                      <div className="h-4 bg-gray-200 rounded w-5/6"></div>
                    </div>
                  </div>
                </div>
                <p className="mt-4 text-gray-500">Loading Wallet Details...</p>
              </div>
            ) : (
              <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
                      </label>
                      <div className="relative w-full">
                        <Input
                          type="text"
                          placeholder="Empty"
                          value={selectedCurrency?.name}
                          readOnly
                          className="bg-gray-100 border border-dashed border-gray-400 text-gray-600 cursor-not-allowed"
                        />
                      </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</label>
                      <div className="relative w-full">
                        <Input
                          type="text"
                          placeholder="Empty"
                          value={selectedGroupNames}
                          readOnly
                          className="bg-gray-100 border border-dashed border-gray-400 text-gray-600 cursor-not-allowed"
                        />
                      </div>
                    </div>
                  </div>

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

export default EditDialog;
