import { apiConfig } from '@/config/api.config';
import { useRef, useState, useCallback, useEffect } from 'react';
import { Alert, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { toast } from 'sonner';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { useManageNotificationContext } from '../hooks/useManageNotificationContext';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { CustomerProps } from '@/pages/master/provider/blocks/AddDialog';
import { Check, ChevronDown } from 'lucide-react';
import { initialStateNotification, selectedNotification, validateFormNotification } from './Types';

const API_URL_CUSTOMER = apiConfig.service_customer;
const API_URL_NOTIFICATION = apiConfig.service_notification;

const AddDialog = () => {
  const { handleAddDialog, showAddDialog } = useManageNotificationContext();
  const { reload } = useDataGrid();
  const { GetData, PostData } = useCallApi();
  const [alert, setAlert] = useState({ show: false, message: '' });
  const isSubmittingRef = useRef(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const [formField, setFormField] = useState<selectedNotification>(initialStateNotification);
  const [open, setOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [customers, setCustomers] = useState<CustomerProps[]>([]);
  const resetForm = () => {
    setFormField({ ...initialStateNotification });
    setIsSubmitting(false);
    setAlert({ show: false, message: '' });
    setErrors({});
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormField({ ...formField, [name]: value });

    if (name === 'all_customer' && value === 'true') {
      setFormField((prev) => ({ ...prev, customers: [] }));
    }

    if (errors[name]) {
      setErrors((prevErrors) => {
        const updatedErrors = { ...prevErrors };
        delete updatedErrors[name];
        return updatedErrors;
      });
    }
  };

  const doCreateNotification = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      if (isSubmittingRef.current) return;
      isSubmittingRef.current = true;
      setIsSubmitting(true);

      try {
        const response = await PostData(`${API_URL_NOTIFICATION}/send`, formField);
        // console.log('send response :', response);

        if (response?.status) {
          handleAddDialog(false);
          resetForm();
          reload();
          toast.success('Notification Send Successfully!');
          const createActivity = {
            module: 'Manage Notification',
            description: `Send New Notification => ${formField.via}`,
            action: 'C'
          };
          doSaveLogActivity(createActivity);
        } else {
          toast.error('Failed to create notification');
          setAlert({ show: true, message: 'Failed to create notification. Please Try Again.' });
        }
      } catch (err) {
        toast.error('Something went wrong');
        console.log(err);
      } finally {
        isSubmittingRef.current = false;
        setIsSubmitting(false);
      }
    },
    [PostData, formField, handleAddDialog, reload]
  );

  const getCustomerList = async (sorting: any) => {
    try {
      sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
      const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
        limit: 100,
        page: 1,
        with_deleted: false,
        order_field: sorting[0].id,
        order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
      });

      setCustomers(response?.data.list);
    } catch (error) {
      console.error('Error fetching customer', error);
    }
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!validateFormNotification(formField, setErrors)) return;
    doCreateNotification(e);
  };

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

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

  return (
    <Dialog open={showAddDialog} onOpenChange={handleAddDialog}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
        <DialogHeader>
          <DialogTitle>Notification - Create</DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <DialogBody className="scrollable">
          <fieldset disabled={isSubmitting}>
            <form onSubmit={handleSubmit} className="space-y-6">
              {alert.show && (
                <Alert variant="danger">
                  <h3>{alert.message}</h3>
                </Alert>
              )}

              <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">
                    Send To<span className="text-red-500">*</span>
                  </label>
                  <div
                    className={`flex gap-6 items-center border rounded-md px-3 py-1 ${
                      errors.all_customer ? 'border-red-500' : 'border-gray-300'
                    }`}
                  >
                    <label className="flex items-center space-x-2">
                      <input
                        type="radio"
                        name="all_customer"
                        value="true"
                        checked={formField.all_customer === 'true'}
                        onChange={handleChange}
                        className="accent-blue-600"
                      />
                      <span>All Customers</span>
                    </label>
                    <label className="flex items-center space-x-2">
                      <input
                        type="radio"
                        name="all_customer"
                        value="false"
                        checked={formField.all_customer === 'false'}
                        onChange={handleChange}
                        className="accent-blue-600"
                      />
                      <span>Selected Customers</span>
                    </label>
                  </div>
                </div>
                {errors.all_customer && (
                  <div className="w-full">
                    <span className="text-red-500 text-xs mt-3 ml-[calc(30%+2rem)] block">
                      {errors.all_customer}
                    </span>
                  </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">Customer</label>
                  <Popover open={open} onOpenChange={setOpen}>
                    <PopoverTrigger asChild>
                      <button
                        type="button"
                        className="input col-span-5 text-left flex justify-between"
                        style={{ color: 'inherit' }}
                        disabled={formField.all_customer !== 'false'}
                      >
                        <span>
                          {formField.customers.length === 0
                            ? 'Select Customers'
                            : `${formField.customers.length} Customers Selected`}
                        </span>
                        <ChevronDown className="w-4 h-4 opacity-70" />
                      </button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[400px] p-0">
                      <Command>
                        <CommandInput placeholder="Search Customer..." />
                        <CommandList
                          className="max-h-[300px] overflow-y-auto"
                          style={{ touchAction: 'pan-y' }}
                          onWheel={(e) => {
                            e.currentTarget.scrollTop += e.deltaY;
                          }}
                        >
                          <CommandEmpty>No Customer found.</CommandEmpty>
                          <CommandGroup>
                            {customers.map((customer) => {
                              const isSelected = formField.customers.includes(customer.id);
                              return (
                                <CommandItem
                                  key={customer.id}
                                  value={customer.username}
                                  onSelect={() => {
                                    const customerId = customer.id;
                                    setFormField((prev) => {
                                      const isSelected = prev.customers.includes(customerId);
                                      return {
                                        ...prev,
                                        customers: isSelected
                                          ? prev.customers.filter((id) => id !== customerId)
                                          : [...prev.customers, customerId]
                                      };
                                    });
                                  }}
                                  className={isSelected ? 'bg-accent font-semibold' : ''}
                                >
                                  <span className="flex items-center gap-2">
                                    {isSelected && <Check className="w-4 h-4 text-green-600" />}
                                    {customer.username}
                                  </span>
                                </CommandItem>
                              );
                            })}
                          </CommandGroup>
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>
                </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>
                  <div
                    className={`flex gap-6 items-center border rounded-md px-3 py-1 ${
                      errors.type ? 'border-red-500' : 'border-gray-300'
                    }`}
                  >
                    {['info', 'promo'].map((type) => (
                      <label key={type} className="flex items-center space-x-2">
                        <input
                          type="radio"
                          name="type"
                          value={type}
                          checked={formField.type === type}
                          onChange={handleChange}
                          className="accent-blue-600"
                        />
                        <span>{type.charAt(0).toUpperCase() + type.slice(1)}</span>
                      </label>
                    ))}
                  </div>
                </div>
                {errors.type && (
                  <div className="w-full">
                    <span className="text-red-500 text-xs mt-3 ml-[calc(30%+2rem)] block">
                      {errors.type}
                    </span>
                  </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">
                    Send Via<span className="text-red-500">*</span>
                  </label>
                  <div
                    className={`flex gap-6 items-center border rounded-md px-3 py-1 ${
                      errors.via ? 'border-red-500' : 'border-gray-300'
                    }`}
                  >
                    <label className="flex items-center space-x-2">
                      <input
                        type="radio"
                        name="via"
                        value="fcm"
                        checked={formField.via === 'fcm'}
                        onChange={handleChange}
                        className="accent-blue-600"
                      />
                      <span>FCM</span>
                    </label>
                    <label className="flex items-center space-x-2">
                      <input
                        type="radio"
                        name="via"
                        value="sms"
                        checked={formField.via === 'sms'}
                        onChange={handleChange}
                        className="accent-blue-600"
                      />
                      <span>SMS</span>
                    </label>
                    <label className="flex items-center space-x-2">
                      <input
                        type="radio"
                        name="via"
                        value="email"
                        checked={formField.via === 'email'}
                        onChange={handleChange}
                        className="accent-blue-600"
                      />
                      <span>E-Mail</span>
                    </label>
                    <label className="flex items-center space-x-2">
                      <input
                        type="radio"
                        name="via"
                        value="whatsapp"
                        checked={formField.via === 'whatsapp'}
                        onChange={handleChange}
                        className="accent-blue-600"
                      />
                      <span>WhatsApp</span>
                    </label>
                  </div>
                </div>
                {errors.via && (
                  <div className="w-full">
                    <span className="text-red-500 text-xs mt-3 ml-[calc(30%+2rem)] block">
                      {errors.via}
                    </span>
                  </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">
                    Number WhatsApp
                  </label>
                  <Input
                    className="input col-span-6"
                    name="content"
                    placeholder="Enter OTP (5 digits)"
                    value={formField.content}
                    onChange={(e) => {
                      const value = e.target.value;
                      if (/^\d{0,5}$/.test(value)) {
                        handleChange(e);
                      }
                    }}
                    disabled={formField.via !== 'whatsapp'}
                    inputMode="numeric"
                    pattern="\d*"
                  />
                </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">Subject</label>
                  <Input
                    className="input col-span-6"
                    name="subject"
                    placeholder="Enter Subject"
                    value={formField.subject}
                    onChange={handleChange}
                    disabled={formField.via !== 'email' && formField.via !== 'fcm'}
                  />
                </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">
                    Content<span className="text-red-500">*</span>
                  </label>
                  <Textarea
                    className={`input col-span-6 ${errors.content ? 'border-red-500' : ''}`}
                    name="content"
                    placeholder="Enter Content Notification"
                    value={formField.content}
                    onChange={handleChange}
                  />
                </div>
                {errors.content && (
                  <div className="w-full">
                    <span className="text-red-500 text-xs mt-3 col-span-8 ml-[calc(30%+2rem)] block">
                      {errors.content}
                    </span>
                  </div>
                )}
              </div>

              <div className="flex justify-end gap-4">
                <Button type="button" variant="outline" onClick={resetForm}>
                  Reset
                </Button>
                <div className="flex justify-end">
                  <Button
                    className={`btn btn-primary ${isSubmitting ? 'opacity-70 cursor-not-allowed' : ''}`}
                    type="submit"
                    disabled={isSubmitting}
                  >
                    {isSubmitting ? 'Creating...' : 'Create Notification'}
                  </Button>
                </div>
              </div>
            </form>
          </fieldset>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddDialog;
