import * as React from "react";
import { useState } from "@wordpress/element";
import { AutoComplete } from "./AutoComplete";
import type { Meta, StoryObj } from "@storybook/react";

const meta: Meta<typeof AutoComplete> = {
  title: "Components/AutoComplete",
  component: AutoComplete,
  argTypes: {
    onItemChange: { action: "onItemChange" },
  },
};

export default meta;

type Story = StoryObj<typeof AutoComplete>;

type Fruit = {
  name: string;
  icon: string;
  category: string;
  description: string;
};


const fetchFruits = async (
  query: string,
  options?: { page?: number; signal?: AbortSignal; selectedValue?: unknown; activeFilter?: string | number; suggestions?: unknown[] }
): Promise<{ items: Fruit[], totalResults: number }> => {
  const page = options?.page || 1;
  const pageSize = 10;

  const url = `http://localhost:4004/api/fruits?query=${query}&page=${page}&page_size=${pageSize}`;

  const response = await fetch(url);
  const { items, totalResults } = await response.json();

  return { items, totalResults };
};

export const Default: Story = {
  args: {
    fetchSuggestions: fetchFruits,
    renderSuggestion: (item: unknown) => {
      const fruit = item as Fruit;

      return (
        <span>{fruit.icon} - {fruit.name}</span>
      );
    },
    valueProp: "name",
    label: "Select a fruit",
  },
  render: ({ fetchSuggestions, renderSuggestion }) => {
    const handleSelect = (item: unknown) => {
      const selectedFruit = item as Fruit;
      console.log("Selected fruit:", selectedFruit);
    };

    return (
      <AutoComplete
        fetchSuggestions={fetchSuggestions}
        renderSuggestion={renderSuggestion}
        valueProp="name"
        label="Select a fruit"
        onItemChange={handleSelect}
      />
    );
  },
};

export const WithValue: Story = {
  render: () => {
    const [selectedFruit, setSelectedFruit] = useState<Fruit>({
      name: "Apple",
      icon: "🍎",
      category: "Fruit",
      description: "A fruit that is round and red or green",
    });

    return (
      <AutoComplete
        defaultValue={selectedFruit}
        fetchSuggestions={fetchFruits}
        selectOnFocus={true}
        help={selectedFruit ? <>{selectedFruit.description}</> : <>Select a fruit</>}
        renderSuggestion={({ name, icon }: Fruit) => (
          <span>
            <span style={{ marginRight: "0.5rem" }}>{icon}</span>
            {name}
          </span>
        )}
        onItemChange={(item: Fruit) => setSelectedFruit(item)}
        valueProp="name"
        label="Select a fruit"
      />
    );
  },
};