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';

interface CurrencyProps {
  ID: string;
  code: string;
  name: string;
  prefix: string;
  status: string;
}

interface GroupProps {
  id: string;
  name: string;
  description: string;
  status: string;
}

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 [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState: {
    name: string;
    description: string;
    status: string;
    group: string[];
    id_currency: string;
  } = {
    name: '',
    description: '',
    status: '',
    group: [],
    id_currency: ''
  };
  const [formField, setFormField] = useState(initialState);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [currencies, setCurrencies] = useState<CurrencyProps[]>([]);
  const [groups, setGroups] = useState<GroupProps[]>([]);

  const resetForm = () => {
    setFormField(initialState);
    setAlert({ show: false, message: '' });
  };

  const handleGroupChange = (groupId: string) => {
    setFormField((prevState) => {
      const isSelected = prevState.group.includes(groupId);

      if (isSelected) {
        // Remove the group if already selected
        return {
          ...prevState,
          group: prevState.group.filter((id) => id !== groupId)
        };
      } else {
        // Add the group if not selected
        return {
          ...prevState,
          group: [...prevState.group, 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('Failed Create Wallet');
          setAlert({ show: true, message: 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 (
      formField.name.trim() === '' ||
      formField.description.trim() === '' ||
      formField.status.trim() === '' ||
      formField.group.length === 0 ||
      formField.id_currency.trim() === ''
    ) {
      setAlert({ show: true, message: 'Please fill in all required fields.' });
      return;
    }

    // console.log(formField);
    doCreateWallet(e);
    setAlert({ show: false, message: '' });
  };

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

  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-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Wallet - Create</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody className="scrollable">
          <div className="flex flex-col">
            {alert.show && (
              <Alert variant="danger">
                <h3>{alert.message}</h3>
              </Alert>
            )}

            <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>
                    <Input
                      type="text"
                      value={formField.name}
                      onChange={(e) => setFormField({ ...formField, name: e.target.value })}
                      placeholder="Wallet Name"
                    />
                  </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>
                    <Input
                      type="text"
                      value={formField.description}
                      onChange={(e) => setFormField({ ...formField, description: e.target.value })}
                      placeholder="Description"
                    />
                  </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>
                    <Select
                      value={formField.status}
                      onValueChange={(value) => setFormField({ ...formField, status: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Status" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">Active</SelectItem>
                        <SelectItem value="N">Inactive</SelectItem>
                      </SelectContent>
                    </Select>
                  </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>
                    <Select
                      value={formField.id_currency}
                      onValueChange={(value) => setFormField({ ...formField, id_currency: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Currency Type" />
                      </SelectTrigger>
                      <SelectContent>
                        {currencies.map((currency) => (
                          <SelectItem key={currency.ID} value={currency.ID}>
                            {currency.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </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="flex flex-wrap gap-3">
                      {groups.map((group) => (
                        <label key={group.id} className="inline-flex items-center">
                          <input
                            type="checkbox"
                            className="h-4 w-4"
                            checked={formField.group.includes(group.id)}
                            onChange={() => handleGroupChange(group.id)}
                          />
                          <span className="ml-2">{group.name}</span>
                        </label>
                      ))}
                    </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;
