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

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

const AddDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { handleAddDialog, showAddDialog } = useManageNotificationContext();
  const { reload } = useDataGrid();
  const { GetData, PostData } = useCallApi();
  const [alert, setAlert] = useState({ show: false, message: '' });

  const initialState = {
    customers: [],
    type: '',
    via: '',
    subject: '',
    content: ''
  };

  const [formField, setFormField] = useState(initialState);
  const [open, setOpen] = useState(false);
  const [customers, setCustomers] = useState<CustomerProps[]>([]);
  const resetForm = () => {
    setFormField(initialState);
    setAlert({ show: false, message: '' });
  };

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

  const doCreateNotification = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const response = await PostData(`${API_URL_NOTIFICATION}/send`, formField);
    console.log('API 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.' });
    }
  };

  // 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 (
      formField.type.trim() === '' ||
      formField.via.trim() === '' ||
      formField.subject.trim() === '' ||
      formField.content.trim() === ''
    ) {
      setAlert({ show: true, message: 'Please fill all required fields.' });
      return;
    }

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

  // 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">
          <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">
                  <label className="flex items-center space-x-2">
                    <input
                      type="radio"
                      name="sendTo"
                      value="all"
                      checked={formField.sendTo === 'all'}
                      onChange={handleChange}
                      className="accent-blue-600"
                    />
                    <span>All Users</span>
                  </label>
                  <label className="flex items-center space-x-2">
                    <input
                      type="radio"
                      name="sendTo"
                      value="selected"
                      checked={formField.sendTo === 'selected'}
                      onChange={handleChange}
                      className="accent-blue-600"
                    />
                    <span>Selected Customers</span>
                  </label>
                </div>
              </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' }}
                    >
                      <span>
                        {customers.find((customer) => customer.id === formField.customers)
                          ?.username || 'Select Customer'}
                      </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) => (
                            <CommandItem
                              key={customer.id}
                              value={customer.username}
                              onSelect={() => {
                                setFormField({
                                  ...formField,
                                  customers: customer.id
                                });
                                setOpen(false);
                              }}
                            >
                              {customer.username}
                            </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">
                  {['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>
            </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">
                  <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>
                </div>
              </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'}
                />
              </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"
                  name="content"
                  placeholder="Enter Content Notification"
                  value={formField.content}
                  onChange={handleChange}
                />
              </div>
            </div>

            <div className="flex justify-end gap-4">
              <Button type="reset" variant="outline" onClick={() => setFormField(initialState)}>
                Reset
              </Button>
              <Button type="submit">Create Notification</Button>
            </div>
          </form>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export default AddDialog;
