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';
import { RefreshCw } from 'lucide-react';

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 [isLoading, setIsLoading] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  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[errors, setErrors] = useState<Record<string, string>>({});
    const validateForm = () => {
      const requiredFields = [
        {key:'name', label: 'Name'},
        {key:'type', label: 'Type'},
        {key:'code', label: 'Code'},
        {key:'description', label: 'Description'},
        {key:'price_point', label: 'Price Point'},
        {key:'price_cash', label: 'Price Cash'},
        {key:'cashback_point', label: 'Cashback Point'},
        {key:'cashback_cash', label: 'Cashback Cash'},
        {key:'status', label: 'Status'},
        {key:'provider', label: 'Provider'},
        {key:'process_on_third_party', label: 'Process On Third Party'} 
      ]
      const newErrors: Record<string, string> = {};
      let isValid = true;
      requiredFields.forEach(({ key, label }) => {
        if (
          formField[key as keyof typeof formField] === '' ||
          formField[key as keyof typeof formField] === null ||
          formField[key as keyof typeof formField] === undefined
        ) {
          newErrors[key] = `${label} is required`;
          toast.error(`${label} is required`);
          isValid = false;
        }
      });
      setErrors(newErrors);
      return isValid;
    }
  const doUpdateProduct = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      setIsSubmitting(true);

      try {
        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: response?.message });
        }
      } catch (error) {
        toast.error('Something went wrong. Please try again.');
      } finally {
        setIsSubmitting(false);
      }
    },
    [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) => {
    setIsLoading(true);

    const minDelay = new Promise((resolve) => setTimeout(resolve, 500));
    const fetchData = GetData(`${API_URL}/product/getdata/${id}`, { id });

    const [response] = await Promise.all([fetchData, minDelay]);
    // 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);
    }
    setIsLoading(false);
  }, []);

  const handleUpdate = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsSubmitting(true);
    if (!validateForm()) {
      setIsSubmitting(false);
      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>
            )}

            {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 Products Details...</p>
              </div>
            ) : (
              <form onSubmit={handleUpdate}>
              <div className="card-body grid gap-5">
                {/* Name */}
                <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>
                    <div className="grow flex flex-col">
                      <Input
                        className={`input ${errors.name ? 'border-red-500' : ''}`}
                        type="text"
                        value={formField.name}
                        onChange={(e) => {
                          setFormField({ ...formField, name: e.target.value });
                          if (e.target.value) setErrors((prev) => ({ ...prev, name: '' }));
                        }}
                      />
                      {errors.name && <span className="text-red-500 text-xs mt-1">{errors.name}</span>}
                    </div>
                  </div>
                </div>
            
                {/* Type */}
                <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>
                    <div className="grow flex flex-col">
                      <Input
                        className={`input ${errors.type ? 'border-red-500' : ''}`}
                        type="text"
                        value={formField.type}
                        onChange={(e) => {
                          setFormField({ ...formField, type: e.target.value });
                          if (e.target.value) setErrors((prev) => ({ ...prev, type: '' }));
                        }}
                      />
                      {errors.type && <span className="text-red-500 text-xs mt-1">{errors.type}</span>}
                    </div>
                  </div>
                </div>
            
                {/* Code */}
                <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>
                    <div className="grow flex flex-col">
                      <Input
                        className={`input ${errors.code ? 'border-red-500' : ''}`}
                        type="text"
                        value={formField.code}
                        onChange={(e) => {
                          setFormField({ ...formField, code: e.target.value });
                          if (e.target.value) setErrors((prev) => ({ ...prev, code: '' }));
                        }}
                      />
                      {errors.code && <span className="text-red-500 text-xs mt-1">{errors.code}</span>}
                    </div>
                  </div>
                </div>
            
                {/* Description */}
                <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="grow flex flex-col">
                      <Input
                        className={`input ${errors.description ? 'border-red-500' : ''}`}
                        type="text"
                        value={formField.description}
                        onChange={(e) => {
                          setFormField({ ...formField, description: e.target.value });
                          if (e.target.value) setErrors((prev) => ({ ...prev, description: '' }));
                        }}
                      />
                      {errors.description && (
                        <span className="text-red-500 text-xs mt-1">{errors.description}</span>
                      )}
                    </div>
                  </div>
                </div>
            
                {/* Price Point */}
                <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>
                    <div className="grow flex flex-col">
                      <NumericFormat
                        className={`input ${errors.price_point ? 'border-red-500' : ''}`}
                        value={formField.price_point ?? ''}
                        thousandSeparator="."
                        decimalSeparator=","
                        allowNegative={false}
                        onValueChange={(values) => {
                          setFormField((prev) => ({
                            ...prev,
                            price_point: values.floatValue ?? ''
                          }));
                          if (values.floatValue !== undefined)
                            setErrors((prev) => ({ ...prev, price_point: '' }));
                        }}
                        placeholder="Enter Price Point"
                      />
                      {errors.price_point && (
                        <span className="text-red-500 text-xs mt-1">{errors.price_point}</span>
                      )}
                    </div>
                  </div>
                </div>
            
                {/* Price Cash */}
                <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>
                    <div className="grow flex flex-col">
                      <NumericFormat
                        className={`input ${errors.price_cash ? 'border-red-500' : ''}`}
                        value={formField.price_cash ?? ''}
                        thousandSeparator="."
                        decimalSeparator=","
                        allowNegative={false}
                        onValueChange={(values) => {
                          setFormField((prev) => ({
                            ...prev,
                            price_cash: values.floatValue ?? ''
                          }));
                          if (values.floatValue !== undefined)
                            setErrors((prev) => ({ ...prev, price_cash: '' }));
                        }}
                        placeholder="Enter Price Cash"
                      />
                      {errors.price_cash && (
                        <span className="text-red-500 text-xs mt-1">{errors.price_cash}</span>
                      )}
                    </div>
                  </div>
                </div>
            
                {/* Cashback Point */}
                <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>
                    <div className="grow flex flex-col">
                      <NumericFormat
                        className={`input ${errors.cashback_point ? 'border-red-500' : ''}`}
                        value={formField.cashback_point ?? ''}
                        thousandSeparator="."
                        decimalSeparator=","
                        allowNegative={false}
                        onValueChange={(values) => {
                          setFormField((prev) => ({
                            ...prev,
                            cashback_point: values.floatValue ?? ''
                          }));
                          if (values.floatValue !== undefined)
                            setErrors((prev) => ({ ...prev, cashback_point: '' }));
                        }}
                        placeholder="Enter Cashback Point"
                      />
                      {errors.cashback_point && (
                        <span className="text-red-500 text-xs mt-1">{errors.cashback_point}</span>
                      )}
                    </div>
                  </div>
                </div>
            
                {/* Cashback Cash */}
                <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>
                    <div className="grow flex flex-col">
                      <NumericFormat
                        className={`input ${errors.cashback_cash ? 'border-red-500' : ''}`}
                        value={formField.cashback_cash ?? ''}
                        thousandSeparator="."
                        decimalSeparator=","
                        allowNegative={false}
                        onValueChange={(values) => {
                          setFormField((prev) => ({
                            ...prev,
                            cashback_cash: values.floatValue ?? ''
                          }));
                          if (values.floatValue !== undefined)
                            setErrors((prev) => ({ ...prev, cashback_cash: '' }));
                        }}
                        placeholder="Enter Cashback Cash"
                      />
                      {errors.cashback_cash && (
                        <span className="text-red-500 text-xs mt-1">{errors.cashback_cash}</span>
                      )}
                    </div>
                  </div>
                </div>
            
                {/* Status */}
                <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="grow flex flex-col">
                      <Select
                        value={formField.status}
                        onValueChange={(e) => {
                          setFormField({ ...formField, status: e });
                          setErrors((prev) => ({ ...prev, status: '' }));
                        }}
                      >
                        <SelectTrigger className={`input ${errors.status ? 'border-red-500' : ''}`}>
                          <SelectValue placeholder="Select a Status" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="Y">Active</SelectItem>
                          <SelectItem value="N">Inactive</SelectItem>
                        </SelectContent>
                      </Select>
                      {errors.status && (
                        <span className="text-red-500 text-xs mt-1">{errors.status}</span>
                      )}
                    </div>
                  </div>
                </div>
            
                {/* Provider */}
                <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
                    </label>
                    <div className="grow flex flex-col">
                      <Select
                        value={formField.provider}
                        onValueChange={(e) => {
                          setFormField({ ...formField, provider: e });
                          setErrors((prev) => ({ ...prev, provider: '' }));
                        }}
                      >
                        <SelectTrigger className={`input ${errors.provider ? 'border-red-500' : ''}`}>
                          <SelectValue placeholder="Select a Provider" />
                        </SelectTrigger>
                        <SelectContent>
                          {providers.map((provider) => (
                            <SelectItem
                              key={provider.provider_id}
                              value={provider.provider_id.toString()}
                            >
                              {provider.provider_name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      {errors.provider && (
                        <span className="text-red-500 text-xs mt-1">{errors.provider}</span>
                      )}
                    </div>
                  </div>
                </div>
            
                {/* Process on Third Party */}
                <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>
                    <div className="grow flex flex-col">
                      <Select
                        value={formField.process_on_third_party}
                        onValueChange={(value) => {
                          setFormField({ ...formField, process_on_third_party: value });
                          setErrors((prev) => ({ ...prev, process_on_third_party: '' }));
                        }}
                      >
                        <SelectTrigger className={`input ${errors.process_on_third_party ? 'border-red-500' : ''}`}>
                          <SelectValue placeholder="Select Status" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="Y">Yes</SelectItem>
                          <SelectItem value="N">No</SelectItem>
                        </SelectContent>
                      </Select>
                      {errors.process_on_third_party && (
                        <span className="text-red-500 text-xs mt-1">{errors.process_on_third_party}</span>
                      )}
                    </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;
