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 PiecesDialog = ({ open, setOpen, onSave, price }: { open: any; setOpen: any, onSave: any, price: any }) => {
  const [options, setOptions] = useState([
    {
      id: 1,
      name: '',
      itemPrice: 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 addOption = () => {
  //   setOptions([
  //     ...options,
  //     {
  //       id: options.length + 1,
  //       name: '',
  //       itemPrice: 0,
  //       additionalPrice: 0,
  //       finalPrice: 0,
  //       isDefault: false
  //     }
  //   ]);
  // };

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

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

  return (
    <Dialog
      open={open?.pieces}
      onOpenChange={(value: any) => setOpen({ ...open, pieces: value })}
    >
      <DialogTrigger asChild>
        <button className="flex w-full items-center justify-between p-4">
          <div>
            <p className="text-start font-medium">Pieces</p>
            <p className="text-sm text-gray-500">
              Various item quantities (e.g 6 or 12 momos,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 Pieces</DialogTitle>
          <Button
            variant="ghost"
            onClick={() => setOpen({ ...open, pieces: 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. 6 or 12 Pieces, etc"
                  className="w-full"
                  value={option.name}
                  onChange={(e) => {
                    const newOptions = [...options];
                    newOptions[index].name = e.target.value;
                    setOptions(newOptions);
                  }}
                  maxLength={20}
                />

                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <label className="mb-2 block text-sm font-medium text-gray-700">
                      Item Price
                    </label>
                    <div className="relative">
                      <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">
                        {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);
                        }} maxLength={5} />
                    </div>
                  </div>

                  <div>
                    <label className="mb-2 block text-sm font-medium text-gray-700">
                      Additional Price
                    </label>
                    <div className="relative flex items-center">
                      <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">
                        {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} />
                      <span className="absolute -left-4 top-1/2 -translate-y-1/2 text-gray-500">
                        +
                      </span>
                    </div>
                  </div>

                  <div>
                    <label className="mb-2 block text-sm font-medium text-gray-700">
                      Final Price
                    </label>
                    <div className="relative flex items-center">
                      <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">
                        {currency}
                      </span>
                      <Input className="pl-8" readOnly value={option.finalPrice} />
                      <span className="absolute -left-4 top-1/2 -translate-y-1/2 text-gray-500">
                        =
                      </span>
                    </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-[var(--primary-brand)] hover:text-[var(--primary-brand)]/80 hover:bg-[var(--primary-brand)]/5 transition-colors"
                      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 PiecesDialog;
