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

const ToppingsDialog = ({
  open,
  setOpen,
  onSave,
  defaultOptions
}: {
  open: any;
  setOpen: any;
  onSave: any;
  defaultOptions?: any;
}) => {
  const [options, setOptions] = useState(
    defaultOptions?.length
      ? defaultOptions
      : [
        {
          id: 1,
          name: '',
          price: 0,
          isCompulsory: false
        }
      ]
  );
  useEffect(() => {
    if (defaultOptions?.length) {
      setOptions(
        defaultOptions.map((opt: any, index: number) => ({
          id: index + 1,
          name: opt?.title || opt?.name || '',
          price: opt?.additional_price || opt?.price || 0,
          isCompulsory: opt?.customer_selection || opt?.is_compulsory
        }))
      );
    }
  }, [defaultOptions]);

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

  const removeOption = (id: number) => {
    setOptions(options.filter((option: any) => option.id !== id));
  };

  const handleSave = () => {
    setOpen({ ...open, toppings: false });
    onSave({ type: 'toppings', option: options });
  };

  return (
    <Dialog
      open={open?.toppings}
      onOpenChange={(value: any) => setOpen({ ...open, toppings: value })}
    >
      <DialogTrigger asChild>
        <button className="flex w-full items-center justify-between p-4">
          <div>
            <p className="text-start font-medium">Toppings</p>
            <p className="text-sm text-gray-500">
              Sauces like pesto or veggies like onions, etc.
            </p>
          </div>
          <ChevronRight className="h-5 w-5" />
        </button>
      </DialogTrigger>
      <DialogContent className="max-w-lg">
        <DialogHeader className="flex flex-row items-center justify-between">
          <DialogTitle>Toppings</DialogTitle>
          <Button
            variant="ghost"
            onClick={() => setOpen({ ...open, toppings: false })}
          >
            <X className="h-6 w-6" />
          </Button>
        </DialogHeader>

        <div className="space-y-6">
          <div className="no-scrollbar max-h-[50vh] overflow-y-auto">
            {options.map((option: any, index: number) => (
              <div key={option.id} className="space-y-4">
                <Input
                  placeholder="Option name like e.g . curd , salad etc"
                  value={option.name}
                  onChange={(e) => {
                    const newOptions = [...options];
                    newOptions[index].name = e.target.value;
                    setOptions(newOptions);
                  }}
                  maxLength={20}
                />

                <div className="space-y-2">
                  <p className="text-sm font-medium">Customer Selection is</p>
                  <div className="flex gap-2">
                    <Button
                      type="button"
                      variant={!option.isCompulsory ? 'default' : 'outline'}
                      className={
                        !option.isCompulsory
                          ? 'bg-yellow-400 text-black hover:bg-[var(--primary-brand)]'
                          : ''
                      }
                      onClick={() => {
                        const newOptions = [...options];
                        newOptions[index].isCompulsory = false;
                        setOptions(newOptions);
                      }}
                    >
                      Optional
                    </Button>
                    <Button
                      type="button"
                      variant={option.isCompulsory ? 'default' : 'outline'}
                      className={
                        option.isCompulsory
                          ? 'bg-yellow-400 text-black hover:bg-[var(--primary-brand)]'
                          : ''
                      }
                      onClick={() => {
                        const newOptions = [...options];
                        newOptions[index].isCompulsory = true;
                        setOptions(newOptions);
                      }}
                    >
                      Compulsory
                    </Button>
                  </div>
                </div>

                <div className="space-y-2">
                  <p className="text-sm font-medium">Additional Price</p>
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2">
                      {currency}
                    </span>
                    <Input
                      className="pl-8"
                      value={option.price}
                      onChange={(e) => {
                        const newOptions = [...options];
                        newOptions[index].price = Number(e.target.value);
                        setOptions(newOptions);
                      }}
                      maxLength={5}
                    />
                  </div>
                </div>
                {options.length > 1 && (
                  <div className="flex justify-end">
                    <Button
                      variant="ghost"
                      className="text-sm text-red-500 hover:text-red-600"
                      onClick={() => removeOption(option.id)}
                    >
                      Remove
                    </Button>
                  </div>
                )}
                {index !== options.length - 1 && (
                  <div className="my-4 border-b border-dashed" />
                )}
              </div>
            ))}
          </div>
          <button
            className="flex w-full items-center justify-center border-2 border-dashed border-[var(--primary-brand)]/20 text-[var(--primary-brand)] hover:text-[var(--primary-brand)]/80 hover:bg-[var(--primary-brand)]/5 hover:border-[var(--primary-brand)]/40 transition-colors py-2 rounded-lg"
            onClick={addOption}
          >
            <Plus className="mr-2 h-4 w-4" />
            ADD MORE OPTION
          </button>

          <Button
            className="w-full bg-yellow-400 text-black hover:bg-[var(--primary-brand)]"
            onClick={handleSave}
          >
            Save
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default ToppingsDialog;
