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 SizeDialog = ({
  open,
  setOpen,
  onSave,
  price,
  initialData,
  showTrigger = true,
}: {
  open: any;
  setOpen: any;
  onSave: any;
  price: any;
  initialData?: any[];
  showTrigger?: boolean;
}) => {
  const [options, setOptions] = useState([
    {
      id: 1,
      title: "",
      itemPrice: 0,
      additionalPrice: 0,
      finalPrice: 0,
      isDefault: true,
    },
  ]);
  useEffect(() => {
    if (initialData && initialData.length > 0) {
      setOptions(
        initialData.map((item, index) => ({
          id: index + 1,
          title: item.title || item.name || "",
          itemPrice: Number(price || 0),
          additionalPrice: Number(item.add_price || item.additionalPrice || 0),
          finalPrice: Number(item.final_price || item.finalPrice || 0),
          isDefault: index === 0,
        }))
      );
    } else {
      setOptions((prevOptions) =>
        prevOptions.map((option) => ({
          ...option,
          itemPrice: Number(price || 0),
          finalPrice: Number(price || 0) + option.additionalPrice,
        }))
      );
    }
  }, [price, initialData, open]);

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

  // const addOption = () => {
  //   setOptions([
  //     ...options,
  //     {
  //       id: options.length + 1,
  //       title: '',
  //       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: "size", option: options });
  };

  return (
    <Dialog
      open={open?.size}
      onOpenChange={(value: any) => setOpen({ ...open, size: value })}
    >
      {showTrigger && (
        <DialogTrigger asChild>
          <button className="flex w-full items-center justify-between p-4">
            <div>
              <p className="text-start font-medium">Size</p>
              <p className="text-sm text-gray-500">
                Item sizes, like bread or pizza (6&quot;, 12&quot;, 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 Size</DialogTitle>
          <Button
            variant="ghost"
            onClick={() => setOpen({ ...open, size: 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 inch, 12 inch, etc."
                  className="w-full"
                  value={option.title}
                  onChange={(e) => {
                    const newOptions = [...options];
                    newOptions[index].title = 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"
            variant={'theme'} onClick={handleSave}
          >
            Save
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default SizeDialog;
