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

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 EditDialog = () => {
  const { showEditDialog, handleEditDialog, selectedWallet } = useManageWalletContext();
  const { reload } = useDataGrid();
  const { GetData, PutData } = useCallApi();
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState: {
    name: string;
    description: string;
    status: string;
    group: string[];
  } = {
    name: '',
    description: '',
    status: '',
    group: []
  };
  const [formField, setFormField] = useState(initialState);
  const [currencies, setCurrencies] = useState<CurrencyProps[]>([]);
  const [groups, setGroups] = useState<GroupProps[]>([]);

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

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

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

      if (response?.status) {
        handleEditDialog(false, null);
        toast.success('Success Update Wallet');
        reload();
      } else {
        toast.error('Failed Update Wallet');
        setAlert({ show: true, message: 'Failed Update Wallet' });
      }
    },
    [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
    };
    // console.log(payload);
    doUpdateWallet(payload);
    setAlert({ show: false, message: '' });
  };

  const doFetchData = useCallback(async (id: string) => {
    const response = await GetData(`${API_URL_MASTER_DATA}/wallet/detail/${id}`, {
      id
    });

    console.log(response);
    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)
          : []
      }));
    }
  }, []);

  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 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) {
      // setFormField((prev) => ({
      //   ...prev,
      //   name: selectedWallet?.Wallet_name,
      //   description: selectedWallet?.Wallet_description,
      //   status: selectedWallet?.Wallet_status,
      //   currency_id: selectedWallet?.Wallet_currency_id,
      //   group: selectedWallet?.Wallet_group
      // }));
      doFetchData(selectedWallet?.Wallet_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">
            {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
                    </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
                    </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</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">Groups</label>
                    <Input type="text" placeholder="Empty" value={selectedGroupNames} readOnly />
                  </div>
                </div>

                <div className="flex justify-end gap-5">
                  <Button type="button" variant="outline" onClick={resetForm}>
                    Reset
                  </Button>
                  <Button variant="default" type="submit">
                    Update
                  </Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;
