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 QuantityDialog = ({ open, setOpen, onSave, price }: { open: any; setOpen: any; onSave: any, price: any }) => {
  const [options, setOptions] = useState([
    {
      id: 1,
      name: '',
      itemPrice: Number(price || 0),
      additionalPrice: 0,
      finalPrice: 0,
      isDefault: true
    }
  ]);

  useEffect(() => {
    setOptions((prevOptions) =>
      prevOptions.map((option) => ({
        ...option,
        itemPrice: Number(price || 0),
        finalPrice: Number(price || 0) + option.additionalPrice
      }))
    );
  }, [price]);

  const addOption = () => {
    setOptions([
      ...options,
      {
        id: options.length + 1,
        name: '',
        itemPrice: Number(price || 0),
        additionalPrice: 0,
        finalPrice: Number(price || 0),
        isDefault: false
      }
    ]);
  };

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

  const handleSave = () => {
    // Handle save logics)
    onSave({ type: "quantity", option: options })
    // onOpenChange(false);
  };

  return (
    <Dialog
      open={open?.quantity}
      onOpenChange={(value: any) => setOpen({ ...open, quantity: value })}
    >
      <DialogTrigger asChild>
        <button className="flex w-full items-center justify-between p-4">
          <div>
            <p className="text-start font-medium">Quantity</p>
            <p className="text-sm text-gray-500">
              Size variations like Small, Medium, Large, 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>Add Quantity</DialogTitle>
          <Button
            variant="ghost"
            onClick={() => setOpen({ ...open, quantity: false })}
          >
            <X className="h-6 w-6" />
          </Button>
        </DialogHeader>

        <div className="space-y-6">
          <div className='max-h-[50vh] overflow-y-auto no-scrollbar'>
            {options.map((option, index) => (
              <div key={option.id} className="space-y-4">
                <Input
                  placeholder="Option Name e.g. Half, Full"
                  className="w-full"
                  value={option.name}
                  onChange={(e) => {
                    const newOptions = [...options];
                    newOptions[index].name = e.target.value;
                    setOptions(newOptions);
                  }}
                  maxLength={20}
                />

                <div className="flex items-center gap-2">
                  <div className="flex-1">
                    <label className="mb-1 block text-sm font-medium">
                      Item Price
                    </label>
                    <div className="relative">
                      <span className="absolute left-3 top-1/2 -translate-y-1/2">
                        {currency}
                      </span>
                      <Input className="pl-8" value={option.itemPrice}
                        onChange={(e) => {
                          const newOptions = [...options];
                          newOptions[index].itemPrice = Number(e.target.value);
                          newOptions[index].finalPrice =
                            Number(newOptions[index].itemPrice) + Number(newOptions[index].additionalPrice);
                          setOptions(newOptions);
                        }} disabled maxLength={5} />
                    </div>
                  </div>

                  <span className="mt-6">+</span>

                  <div className="flex-1">
                    <label className="mb-1 block text-sm font-medium">
                      Additional Price
                    </label>
                    <div className="relative">
                      <span className="absolute left-3 top-1/2 -translate-y-1/2">
                        {currency}
                      </span>
                      <Input className="pl-8" value={option.additionalPrice}
                        onChange={(e) => {
                          const newOptions = [...options];
                          newOptions[index].additionalPrice = Number(e.target.value);
                          newOptions[index].finalPrice = Number(newOptions[index].itemPrice) + Number(newOptions[index].additionalPrice);
                          setOptions(newOptions);
                        }} maxLength={5} />
                    </div>
                  </div>

                  <span className="mt-6">=</span>

                  <div className="flex-1">
                    <label className="mb-1 block text-sm font-medium">
                      Final Price
                    </label>
                    <div className="relative">
                      <span className="absolute left-3 top-1/2 -translate-y-1/2">
                        {currency}
                      </span>
                      <Input className="pl-8" readOnly value={option.finalPrice} />
                    </div>
                  </div>
                </div>

                <div className="flex justify-end">
                  {option.isDefault ? (
                    <span className="text-sm text-[var(--primary-brand)]">
                      Default option
                    </span>
                  ) : (
                    <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
            variant="ghost"
            className="w-full 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"
            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 QuantityDialog;
