import { Alert, useDataGrid } from '@/components';
import { useManageProductsContext } from '../hooks/useManageProductsContext';
import { useCallApi } from '@/hooks';
import { getAuth } from '@/auth';
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 { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { NumericFormat } from 'react-number-format';

interface ProviderProps {
  provider_id: string;
  provider_name: string;
}

const API_URL = apiConfig.service_master_data;
const EditDialog = () => {
  const { showEditDialog, handleEditDialog, selectedProducts } = useManageProductsContext();
  const { reload } = useDataGrid();
  const { PutData, GetData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const created_time = new Date();
  const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState: {
    name: string;
    code: string;
    type: string;
    description: string;
    price_point: string | number | null;
    price_cash: string | number | null;
    cashback_point: string | number | null;
    cashback_cash: string | number | null;
    status: string;
    provider: string;
    process_on_third_party: string;
    updated_by: string;
    updated_at: string;
  } = {
    name: '',
    code: '',
    type: '',
    description: '',
    price_point: null,
    price_cash: null,
    cashback_point: null,
    cashback_cash: null,
    status: '',
    provider: '',
    process_on_third_party: '',
    updated_by: '',
    updated_at: ''
  };
  const [formField, setFormField] = useState(initialState);
  const [providers, setProviders] = useState<ProviderProps[]>([]);

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

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

      const response = await PutData(`${API_URL}/product/update/${selectedProducts}`, formField);

      if (response?.status) {
        resetForm();
        handleEditDialog(false, null);
        toast.success('Product updated successfully.');
        reload();

        const createActivity = {
          module: 'Manage Products',
          description: `Edit Product => ${selectedProducts}`,
          action: 'U'
        };

        doSaveLogActivity(createActivity);
      } else {
        toast.error('Failed to update Product. Please try again.');
        setAlert({ show: true, message: 'Failed to update Product. Please try again.' });
      }
    },
    [selectedProducts, formField]
  );

  const doFetchProvider = useCallback(async (sorting: any) => {
    try {
      const response = await GetData(`${API_URL}/provider/list`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
      });
      // console.log('PROVIDER: ', response?.data);
      setProviders(response?.data.list);
    } catch (error) {
      console.error('Error fetching provider', error);
    }
  }, []);

  const doFetchData = useCallback(async (id: string) => {
    const response = await GetData(`${API_URL}/product/getdata/${id}`, { id });
    // console.log(response);

    if (response?.status) {
      setFormField((prev) => ({
        ...prev,
        name: response.data?.name,
        type: response.data?.type,
        code: response.data?.code,
        description: response.data?.description,
        price_point: response.data?.price_point,
        price_cash: response.data?.price_cash,
        cashback_point: response.data?.cashback_point,
        cashback_cash: response.data?.cashback_cash,
        status: response.data?.status,
        provider: response.data?.provider?.id,
        process_on_third_party: response.data?.process_on_third_party
      }));
    } else {
      setFormField(initialState);
    }
  }, []);

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

    if (
      formField.name.trim() === '' ||
      formField.type.trim() === '' ||
      formField.code.trim() === '' ||
      formField.description.trim() === '' ||
      formField.price_point === null ||
      formField.price_cash === null ||
      formField.cashback_point === null ||
      formField.cashback_cash === null ||
      formField.status.trim() === '' ||
      formField.provider.trim() === '' ||
      formField.process_on_third_party.trim() === '' ||
      formField.updated_by.trim() === '' ||
      formField.updated_at.trim() === ''
    ) {
      setAlert({ show: true, message: 'Please fill in all required fields.' });
      return;
    }

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

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

  useEffect(() => {
    if (selectedProducts) {
      doFetchData(selectedProducts);
    }
  }, [selectedProducts]);

  useEffect(() => {
    if (showEditDialog) {
      setFormField({
        ...formField,
        updated_by: parsedUser.username,
        updated_at: formattedTime
      });
    }
  }, [formattedTime]);

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

  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>Product - Update</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody className="overflow-y-auto">
          <div className="flex flex-col">
            {alert.show && (
              <Alert variant="danger">
                <h3>{alert.message}</h3>
              </Alert>
            )}

            <form onSubmit={handleUpdate}>
              <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">
                      Name<span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="text"
                      value={formField.name}
                      onChange={(e) => setFormField({ ...formField, name: e.target.value })}
                    />
                  </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">
                      Type<span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="text"
                      value={formField.type}
                      onChange={(e) => setFormField({ ...formField, type: e.target.value })}
                    />
                  </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">
                      Code<span className="text-red-500">*</span>
                    </label>
                    <Input
                      className="input"
                      type="text"
                      value={formField.code}
                      onChange={(e) => setFormField({ ...formField, code: e.target.value })}
                    />
                  </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
                      className="input"
                      type="text"
                      value={formField.description}
                      onChange={(e) => setFormField({ ...formField, description: e.target.value })}
                    />
                  </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">
                      Price Point<span className="text-red-500">*</span>
                    </label>
                    <NumericFormat
                      className="input"
                      value={formField.price_point ?? ''}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          price_point: values.floatValue !== undefined ? values.floatValue : ''
                        }));
                      }}
                      placeholder="Enter Price Point"
                    />
                  </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">
                      Price Cash<span className="text-red-500">*</span>
                    </label>
                    <NumericFormat
                      className="input"
                      value={formField.price_cash ?? ''}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          price_cash: values.floatValue !== undefined ? values.floatValue : ''
                        }));
                      }}
                      placeholder="Enter Price Cash"
                    />
                  </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">
                      Cashback Point<span className="text-red-500">*</span>
                    </label>
                    <NumericFormat
                      className="input"
                      value={formField.cashback_point ?? ''}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          cashback_point: values.floatValue !== undefined ? values.floatValue : ''
                        }));
                      }}
                      placeholder="Enter Cashback Point"
                    />
                  </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">
                      Cashback Cash<span className="text-red-500">*</span>
                    </label>
                    <NumericFormat
                      className="input"
                      value={formField.cashback_cash ?? ''}
                      thousandSeparator="."
                      decimalSeparator=","
                      allowNegative={false}
                      onValueChange={(values) => {
                        setFormField((prev) => ({
                          ...prev,
                          cashback_cash: values.floatValue !== undefined ? values.floatValue : ''
                        }));
                      }}
                      placeholder="Enter Cashback Cash"
                    />
                  </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={(e) => setFormField({ ...formField, status: e })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select a 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">
                      Provider ID
                    </label>
                    <Select
                      value={formField.provider}
                      onValueChange={(e) => setFormField({ ...formField, provider: e })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select a Provider" />
                      </SelectTrigger>
                      <SelectContent>
                        {providers.map((provider) => (
                          <SelectItem key={provider.provider_id} value={provider.provider_id}>
                            {provider.provider_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">
                      Process on Third Party<span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={formField.process_on_third_party}
                      onValueChange={(value) =>
                        setFormField({ ...formField, process_on_third_party: value })
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Status" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">Yes</SelectItem>
                        <SelectItem value="N">No</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

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

export default EditDialog;
