import { getAuth } from '@/auth';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useManageProductsContext } from '../hooks/useManageProductsContext';
import { useCallApi } from '@/hooks';
import { Alert, useDataGrid } from '@/components';
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: number;
  provider_name: string;
}

const API_URL = apiConfig.service_master_data;
const AddDialog = () => {
  const parentRef = useRef<any | null>(null);
  const parsedUser = getAuth()?.user;
  const { showAddDialog, handleAddDialog, selectedProducts } = useManageProductsContext();
  const { PostData, GetData } = useCallApi();
  const { reload } = useDataGrid();
  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;
    created_by: string;
    created_at: string;
  } = {
    name: '',
    code: '',
    type: '',
    description: '',
    price_point: null,
    price_cash: null,
    cashback_point: null,
    cashback_cash: null,
    status: '',
    provider: '',
    process_on_third_party: '',
    created_by: '',
    created_at: ''
  };
  const [formField, setFormField] = useState(initialState);
  const [providers, setProviders] = useState<ProviderProps[]>([]);
  const created_time = new Date();
  const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');

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

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

      const response = await PostData(`${API_URL}/product/create`, formField);

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

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

        doSaveLogActivity(createActivity);
      } else {
        toast.error('Failed Create Product');
        setAlert({ show: true, message: response?.message });
      }
    },
    [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 handleSubmit = (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.created_by.trim() === '' ||
      formField.created_at.trim() === ''
    ) {
      setAlert({ show: true, message: 'Please fill in all required fields.' });
      return;
    }

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

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

  useEffect(() => {
    if (showAddDialog) {
      setFormField({
        ...formField,
        created_by: parsedUser.username,
        created_at: formattedTime
      });
    }
  }, [formattedTime]);

  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>Product - Create</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody ref={parentRef} className="overflow-y-auto">
          <div className="flex flex-col">
            {alert.show && (
              <div className="fixed top-[70px] left-1/2 -translate-x-1/2 -translate-y-1/2 z-50">
                <Alert variant="danger">
                  <h3>{alert.message}</h3>
                </Alert>
              </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">
                      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={(value) => setFormField({ ...formField, status: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Status" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Y">Yes</SelectItem>
                        <SelectItem value="N">No</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={(value) =>
                        setFormField({ ...formField, provider: value.toString() })
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Select Provider" />
                      </SelectTrigger>
                      <SelectContent>
                        {providers.map((provider) => (
                          <SelectItem
                            key={provider.provider_id}
                            value={provider.provider_id.toString()}
                          >
                            {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 AddDialog;
