import React, { 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 { Textarea } from '@/components/ui/textarea';
import { currency } from '@/lib/utils';

const AddMoreDialog = ({
  open,
  setOpen,
  onAdd
}: {
  open: any;
  setOpen: any;
  onAdd: any;
}) => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [options, setOptions] = useState([
    {
      id: 1,
      name: '',
      price: 0,
      isCompulsory: true
    }
  ]);

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

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

  const toggleCompulsory = (id: number) => {
    setOptions(
      options.map((option) =>
        option.id === id
          ? { ...option, isCompulsory: !option.isCompulsory }
          : option
      )
    );
  };

  const handleSave = () => {
    if (!title) return;
    let data = {
      name: title,
      desc: description,
      options: options
    };
    onAdd(data);
    // Reset state for next use
    setTitle('');
    setDescription('');
    setOptions([{ id: 1, name: '', price: 0, isCompulsory: true }]);
  };

  return (
    <Dialog
      open={open?.addmore}
      onOpenChange={(value: any) => setOpen({ ...open, addmore: value })}
    >
      <DialogTrigger asChild>
        <button className="flex w-full items-center justify-between p-4 text-start">
          <div>
            <p className="font-medium">Make your own</p>
            <p className="text-sm text-gray-500">
              Create your own variation if no template fits.
            </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 Customization Group</DialogTitle>
          <Button
            variant="ghost"
            onClick={() => setOpen({ ...open, addmore: false })}
          >
            <X className="h-6 w-6" />
          </Button>
        </DialogHeader>

        <div className="no-scrollbar max-h-[70vh] space-y-6 overflow-y-auto pr-2">
          <div className="space-y-4">
            <div>
              <label className="text-sm font-medium">Title of the group</label>
              <Input
                placeholder="e.g. Pizza Crust"
                className="mt-1"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
              />
            </div>

            <div>
              <label className="text-sm font-medium">
                Description (Optional)
              </label>
              <Textarea
                placeholder="Enter description..."
                className="mt-1 w-full rounded-md p-2"
                rows={2}
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              />
            </div>

            <div className="border-t pt-4">
              <label className="mb-4 block text-sm font-semibold">
                Options / Variants
              </label>

              {options.map((option, index) => (
                <div
                  key={option.id}
                  className="mb-6 space-y-4 rounded-md border p-3 bg-gray-50/50"
                >
                  <Input
                    placeholder="Option name e.g. Thin Crust"
                    value={option.name}
                    onChange={(e) => {
                      const newOptions = [...options];
                      newOptions[index].name = e.target.value;
                      setOptions(newOptions);
                    }}
                  />

                  <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={`transition-colors ${option.isCompulsory
                          ? 'bg-[var(--primary-brand)] hover:bg-[var(--primary-brand)]/90 text-white border-[var(--primary-brand)]'
                          : ''
                          }`}
                        onClick={() => toggleCompulsory(option.id)}
                      >
                        Compulsory
                      </Button>
                      <Button
                        type="button"
                        variant={!option.isCompulsory ? 'default' : 'outline'}
                        className={`transition-colors ${!option.isCompulsory
                          ? 'bg-[var(--primary-brand)] hover:bg-[var(--primary-brand)]/90 text-white border-[var(--primary-brand)]'
                          : ''
                          }`}
                        onClick={() => toggleCompulsory(option.id)}
                      >
                        Optional
                      </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 text-gray-500">
                        {currency}
                      </span>
                      <Input
                        className="pl-8"
                        type="number"
                        value={option.price}
                        onChange={(e) => {
                          const newOptions = [...options];
                          newOptions[index].price = Number(e.target.value);
                          setOptions(newOptions);
                        }}
                        placeholder="0"
                      />
                    </div>
                  </div>

                  {options.length > 1 && (
                    <div className="flex justify-end">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-red-500 hover:text-red-600 hover:bg-red-50"
                        onClick={() => removeOption(option.id)}
                      >
                        Remove Option
                      </Button>
                    </div>
                  )}
                </div>
              ))}

              <Button
                variant="outline"
                className="w-full border-2 border-dashed border-[var(--primary-brand)]/20 text-[var(--primary-brand)] 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 ANOTHER OPTION
              </Button>
            </div>
          </div>

          <Button
            className="w-full h-11 bg-[var(--primary-brand)] hover:bg-[var(--primary-brand)]/30 text-white font-semibold"
            variant={'theme'}
            onClick={handleSave}
            disabled={!title || options.some((opt) => !opt.name)}
          >
            Save Customization
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default AddMoreDialog;
