import React, { useState, useEffect } from 'react';
import { ChevronRight, Plus, X } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { currency } from '@/lib/utils';

import { useGlobalContext } from '@/context/Provider';

interface OptionItem {
  id: number;
  name: string;
  price: number;
}

const AddonDialog = ({
  open,
  setOpen,
  onSave,
  initialData,
  showTrigger = true,
}: {
  open: any;
  setOpen: any;
  onSave: any;
  initialData?: any;
  showTrigger?: boolean;
}) => {
  const { Toast } = useGlobalContext();
  const [minSelection, setMinSelection] = useState<number>(0);
  const [maxSelection, setMaxSelection] = useState<number>(1);
  const [options, setOptions] = useState<OptionItem[]>([
    { id: 1, name: '', price: 0 }
  ]);

  useEffect(() => {
    const isModalOpen = open?.addon;
    if (isModalOpen) {
      if (initialData && (Array.isArray(initialData) ? initialData.length > 0 : Boolean(initialData))) {
        const dataArray = Array.isArray(initialData)
          ? initialData
          : initialData.options || [];

        const firstItem = Array.isArray(initialData) ? initialData[0] : initialData;
        setMinSelection(Number(firstItem?.min_selection ?? initialData?.min_selection ?? 0));
        setMaxSelection(Number(firstItem?.max_selection ?? initialData?.max_selection ?? 1));

        if (dataArray.length > 0) {
          setOptions(
            dataArray.map((item: any, index: number) => ({
              id: item.id || index + 1,
              name: item.name || item.title || '',
              price: Number(item.price ?? item.additional_price ?? 0)
            }))
          );
        } else {
          setOptions([{ id: 1, name: '', price: 0 }]);
        }
      } else {
        setMinSelection(0);
        setMaxSelection(1);
        setOptions([{ id: 1, name: '', price: 0 }]);
      }
    }
  }, [initialData, open?.addon]);

  const addOption = () => {
    setOptions([
      ...options,
      {
        id: options.length + 1,
        name: '',
        price: 0
      }
    ]);
  };

  const removeOption = (id: number) => {
    if (options.length <= 1) return;
    setOptions(options.filter((option) => option.id !== id));
  };

  const handleSave = () => {
    const optionsCount = options.length;
    const minVal = Number(minSelection ?? 0);
    const maxVal = Number(maxSelection ?? 1);

    if (minVal > optionsCount) {
      Toast.error(`Min Selection (${minVal}) cannot be greater than the number of options added (${optionsCount})`);
      return;
    }

    if (maxVal > optionsCount) {
      Toast.error(`Max Selection (${maxVal}) cannot be greater than the number of options added (${optionsCount})`);
      return;
    }

    if (maxVal < minVal) {
      Toast.error('Max Selection cannot be less than Min Selection');
      return;
    }

    const formattedOptions = options.map((opt) => ({
      id: opt.id,
      name: opt.name.trim(),
      title: opt.name.trim(),
      price: Number(opt.price || 0),
      additional_price: Number(opt.price || 0),
      min_selection: minVal,
      max_selection: maxVal
    }));

    setOpen({ ...open, addon: false });
    onSave({ type: 'addons', option: formattedOptions });
  };

  return (
    <>
      {showTrigger && (
        <button
          type="button"
          className="flex w-full items-center justify-between p-4 text-left cursor-pointer hover:bg-gray-50/50 transition-colors"
          onClick={() => setOpen({ ...open, addon: true })}
        >
          <div>
            <p className="text-start font-medium text-gray-900">Add-on</p>
            <p className="text-sm text-gray-500">
              Sauces like garlic sauce, pickles, etc.
            </p>
          </div>
          <ChevronRight className="h-5 w-5 text-gray-400" />
        </button>
      )}

      <Dialog
        open={open?.addon}
        onOpenChange={(value: any) => setOpen({ ...open, addon: value })}
      >
        <DialogContent className="max-w-lg p-6 bg-white rounded-2xl shadow-xl overflow-hidden border-0">
          <DialogHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
            <DialogTitle className="text-xl font-bold text-gray-900">
              Add on
            </DialogTitle>
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8 rounded-full text-gray-400 hover:text-gray-600"
              onClick={() => setOpen({ ...open, addon: false })}
            >
              <X className="h-5 w-5" />
            </Button>
          </DialogHeader>

          <div className="no-scrollbar max-h-[75vh] space-y-5 overflow-y-auto pt-4 pr-1">
            {/* Customer Selection Limit */}
            <div className="rounded-xl border border-gray-100 bg-gray-50/60 p-4 space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm font-bold text-gray-900">
                  Customer Selection Limit
                </span>
                <span className="text-xs text-gray-500 font-normal">
                  How many options customer can select
                </span>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">
                    Min Selection
                  </label>
                  <Input
                    type="number"
                    min="0"
                    maxLength={2}
                    className="h-10 bg-white rounded-lg border-gray-200 text-sm font-medium"
                    value={minSelection}
                    onChange={(e) => {
                      const val = e.target.value.slice(0, 2);
                      setMinSelection(val === '' ? '' as any : Math.max(0, Number(val)));
                    }}
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">
                    Max Selection
                  </label>
                  <Input
                    type="number"
                    min="1"
                    maxLength={2}
                    className="h-10 bg-white rounded-lg border-gray-200 text-sm font-medium"
                    value={maxSelection}
                    onChange={(e) => {
                      const val = e.target.value.slice(0, 2);
                      setMaxSelection(val === '' ? '' as any : Math.max(0, Number(val)));
                    }}
                  />
                </div>
              </div>
            </div>

            {/* Options / Variants */}
            <div className="space-y-3 pt-2">
              {options.map((option, index) => (
                <div
                  key={option.id}
                  className="space-y-3 rounded-xl border border-gray-200 p-4 bg-white shadow-sm"
                >
                  <div>
                    <Input
                      placeholder="Add-on Name e.g. Curd"
                      className="h-10 rounded-lg border-gray-200 text-sm"
                      value={option.name}
                      onChange={(e) => {
                        const newOptions = [...options];
                        newOptions[index].name = e.target.value;
                        setOptions(newOptions);
                      }}
                    />
                  </div>

                  <div>
                    <label className="block text-xs font-semibold text-gray-700 mb-1">
                      Additional Price
                    </label>
                    <div className="relative">
                      <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 font-medium text-sm">
                        {currency}
                      </span>
                      <Input
                        type="number"
                        min="0"
                        maxLength={4}
                        className="h-10 pl-14 bg-white rounded-lg border-gray-200 text-sm font-medium"
                        value={option.price}
                        onChange={(e) => {
                          const val = e.target.value.slice(0, 4);
                          const newOptions = [...options];
                          newOptions[index].price = val === '' ? '' as any : Math.max(0, Number(val));
                          setOptions(newOptions);
                        }}
                        placeholder="0"
                      />
                    </div>
                  </div>

                  {options.length > 1 && (
                    <div className="flex justify-end">
                      <button
                        type="button"
                        className="text-xs font-semibold text-red-500 hover:text-red-700 transition-colors"
                        onClick={() => removeOption(option.id)}
                      >
                        Remove Option
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>

            <Button
              type="button"
              variant="outline"
              className="w-full h-11 border-2 border-dashed border-[var(--primary-brand)]/20 text-[var(--primary-brand)] font-semibold text-xs tracking-wide uppercase hover:bg-[var(--primary-brand)]/5 hover:border-[var(--primary-brand)]/40 transition-colors rounded-xl flex items-center justify-center gap-1.5"
              onClick={addOption}
            >
              <Plus className="h-4 w-4" /> ADD MORE OPTION
            </Button>

            <Button
              type="button"
              className="h-11 w-full bg-[var(--primary-brand)] font-semibold text-white hover:bg-[var(--primary-brand)]/90 rounded-xl text-sm transition-colors"
              onClick={handleSave}
              disabled={options.some((opt) => !opt.name.trim())}
            >
              Save
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
};

export default AddonDialog;
