import React from "react";
import { Meta } from "@storybook/react";
import { SchedulerProps } from "./SchedulerProps";
import Scheduler from "./Scheduler";

import { guid } from "@progress/kendo-react-common";
import { timezoneNames } from "@progress/kendo-date-math";
import {
  DropDownList as KendoDropDownList,
  DropDownListChangeEvent as KendoDropDownListChangeEvent,
} from "@progress/kendo-react-dropdowns";
import {
  load,
  loadMessages,
  IntlProvider as KendoIntlProvider,
  LocalizationProvider as KendoLocalizationProvider,
} from "@progress/kendo-react-intl";
import {
  TimelineView as KendoTimelineView,
  DayView as KendoDayView,
  WeekView as KendoWeekView,
  MonthView as KendoMonthView,
  AgendaView as KendoAgendaView,
  SchedulerViewChangeEvent as KendoSchedulerViewChangeEvent,
  SchedulerDateChangeEvent as KendoSchedulerDateChangeEvent,
  SchedulerDataChangeEvent as KendoSchedulerDataChangeEvent,
} from "@progress/kendo-react-scheduler";

import weekData from "cldr-core/supplemental/weekData.json";
import currencyData from "cldr-core/supplemental/currencyData.json";
import likelySubtags from "cldr-core/supplemental/likelySubtags.json";
import numbers from "cldr-numbers-full/main/es/numbers.json";
import dateFields from "cldr-dates-full/main/es/dateFields.json";
import currencies from "cldr-numbers-full/main/es/currencies.json";
import caGregorian from "cldr-dates-full/main/es/ca-gregorian.json";
import timeZoneNames from "cldr-dates-full/main/es/timeZoneNames.json";

import "@progress/kendo-date-math/tz/Etc/UTC";
import "@progress/kendo-date-math/tz/Europe/Sofia";
import "@progress/kendo-date-math/tz/Europe/Madrid";
import "@progress/kendo-date-math/tz/Asia/Dubai";
import "@progress/kendo-date-math/tz/Asia/Tokyo";
import "@progress/kendo-date-math/tz/America/New_York";
import "@progress/kendo-date-math/tz/America/Los_Angeles";

import esMessages from "./mockData/es.json";
import {
  sampleDataWithCustomSchema,
  displayDate,
  customModelFields,
} from "./mockData/events-utc";

load(
  likelySubtags,
  currencyData,
  weekData,
  numbers,
  currencies,
  caGregorian,
  dateFields,
  timeZoneNames
);
loadMessages(esMessages, "es-ES");

export default {
  title: "Design System/Scheduler",
  component: Scheduler,
  tags: ["autodocs"],
  parameters: {
    docs: {
      description: {
        component:
          'The KendoReact Scheduler provides out-of-the-box support for timezone conversion, resources visualization, grouping, editing, and recurring events. \n\n```javascript\nimport { Scheduler } from "@renault-ui-library"\n```',
      },
    },
  },
  argTypes: {
    dataTestId: {
      control: { type: "text" },
      description: "Specifies the data-test-id attribute for testing purposes.",
    },
    ariaLabel: {
      control: { type: "text" },
      description:
        "The aria-label attribute to be applied to the Scheduler component.",
    },
    ariaLabelledby: {
      control: { type: "text" },
      description:
        "The aria-labelledby attribute to be applied to the Scheduler component.",
    },
    children: {
      control: { type: "object" },
      description:
        "Specify the available view components as children and the Scheduler will match the currently selected view and render it.",
    },
    className: {
      control: { type: "text" },
      description:
        "Specifies the className attribute of the wrapping element of the Scheduler.",
    },
    data: {
      control: { type: "array" },
      description:
        "Sets the data of the Scheduler component. The data is then parsed and rendered as visual Scheduler items.",
    },
    date: {
      control: { type: "date" },
      description:
        "Sets the current selected Date. The current selected date is passed to the selected view and transformed into a range.",
    },
    defaultDate: {
      control: { type: "date" },
      description:
        "Sets a default selected Date. The defaultDate property is used to specify the initial rendered date, while still remaining in an uncontrolled mode.",
    },
    defaultView: {
      control: { type: "text" },
      description:
        "Sets the initially selected view. Available values are: day, week, month, agenda, timeline.",
    },
    editable: {
      control: { type: "boolean" },
      description:
        "Sets if the Scheduler component is editable. The value can be either a boolean or an Object to specify different types of editing.",
    },
    editItem: {
      control: { type: "object" },
      description:
        "Overrides the default editItem. Specifying the editItem property of a specific view will override this property.",
    },
    editSlot: {
      control: { type: "object" },
      description:
        "Overrides the default editSlot component. Specifying the editSlot property of a specific view will override this property.",
    },
    editTask: {
      control: { type: "object" },
      description:
        "Overrides the default editTask. Specifying the editTask property of a specific view will override this property. Currently, the viewTask is being used in the AgendaView only.",
    },
    footer: {
      control: { type: "object" },
      description: "Overrides the default footer component of the Scheduler.",
    },
    group: {
      control: { type: "object" },
      description: "Specifies the groups of the Scheduler.",
    },
    header: {
      control: { type: "object" },
      description: "Overrides the default header component of the Scheduler.",
    },
    height: {
      control: { type: "text" },
      description: "Sets the height of the Scheduler.",
    },
    id: {
      control: { type: "text" },
      description: "Specifies the id of the wrapping element of the Scheduler.",
    },
    item: {
      control: { type: "object" },
      description:
        "Overrides the default item. Specifying the item property of a specific view will override this property.",
    },
    modelFields: {
      control: { type: "object" },
      description:
        "The names of the model fields from which the Scheduler will read its data.",
    },
    resources: {
      control: { type: "array" },
      description: "Specifies the resources of the Scheduler.",
    },
    role: {
      control: { type: "text" },
      description:
        "Specifies the role attribute of the Scheduler wrapping element.",
    },
    rtl: {
      control: { type: "boolean" },
      description: "Force a RTL mode.",
    },
    slot: {
      control: { type: "object" },
      description:
        "Overrides the default slot component. Specifying the slot property of a specific view will override this property.",
    },
    style: {
      control: { type: "object" },
      description:
        "Specifies the style object of the wrapping element of the Scheduler.",
    },
    tabIndex: {
      control: { type: "number" },
      description:
        "Specifies the tabIndex attribute of the wrapping element of the Scheduler.",
    },
    task: {
      control: { type: "object" },
      description:
        "Overrides the default task. Specifying the task property of a specific view will override this property. Currently, the task is being used in the AgendaView only.",
    },
    timezone: {
      control: { type: "text" },
      description:
        "Specifies the id of the timezone that will be displayed in the Scheduler. Defaults to Etc/UTC.",
    },
    view: {
      control: { type: "text" },
      description:
        "Sets the currently selected view. The value is matched with the name property of the view.",
    },
    viewItem: {
      control: { type: "object" },
      description:
        "Overrides the default viewItem. Specifying the viewItem property of a specific view will override this property.",
    },
    viewSlot: {
      control: { type: "object" },
      description:
        "Overrides the default viewSlot component. Specifying the viewSlot property of a specific view will override this property.",
    },
    viewTask: {
      control: { type: "object" },
      description:
        "Overrides the default viewTask. Specifying the viewTask property of a specific view will override this property. Currently, the viewTask is being used in the AgendaView only.",
    },
    onDataChange: {
      control: { type: "function" },
      description:
        "Called each time when editing occurs. To enable editing set the editable property to true or an EditableProp.",
    },
    onDateChange: {
      control: { type: "function" },
      description: "Called when new date is selected.",
    },
    onViewChange: {
      control: { type: "function" },
      description: "Called when new view is selected.",
    },
  },
} as Meta;

export const Default = (args: SchedulerProps): JSX.Element => {
  const timezones = React.useMemo(() => timezoneNames(), []);
  const locales = [
    { language: "en-US", locale: "en" },
    { language: "es-ES", locale: "es" },
  ];

  const [view, setView] = React.useState("day");
  const [date, setDate] = React.useState(displayDate);
  const [locale, setLocale] = React.useState(locales[0]);
  const [timezone, setTimezone] = React.useState("Etc/UTC");
  const [orientation, setOrientation] = React.useState<
    "horizontal" | "vertical"
  >("horizontal");
  const [data, setData] = React.useState(sampleDataWithCustomSchema);

  const handleViewChange = React.useCallback(
    (event: KendoSchedulerViewChangeEvent) => {
      setView(event.value);
    },
    [setView]
  );

  const handleDateChange = React.useCallback(
    (event: KendoSchedulerDateChangeEvent) => {
      setDate(event.value);
    },
    [setDate]
  );

  const handleLocaleChange = React.useCallback(
    (event: KendoDropDownListChangeEvent) => {
      setLocale(event.target.value);
    },
    [setLocale]
  );

  const handleTimezoneChange = React.useCallback(
    (event: KendoDropDownListChangeEvent) => {
      setTimezone(event.target.value);
    },
    [setTimezone]
  );

  const handleOrientationChange = React.useCallback((event: any) => {
    setOrientation(event.target.getAttribute("data-orientation"));
  }, []);

  const handleDataChange = React.useCallback(
    ({ created, updated, deleted }: KendoSchedulerDataChangeEvent) => {
      setData((old) =>
        old
          .filter(
            (item) =>
              deleted.find((current) => current.TaskID === item.TaskID) ===
              undefined
          )
          .map(
            (item) =>
              updated.find((current) => current.TaskID === item.TaskID) || item
          )
          .concat(
            created.map((item) => Object.assign({}, item, { TaskID: guid() }))
          )
      );
    },
    [setData]
  );

  return (
    <>
      <div style={{ display: "flex", gap: "2rem", marginBottom: "2rem" }}>
        <div style={{ display: "flex", flexDirection: "column" }}>
          <h4>Timezone:</h4>
          <KendoDropDownList
            value={timezone}
            onChange={handleTimezoneChange}
            data={timezones}
          />
        </div>
        <div style={{ display: "flex", flexDirection: "column" }}>
          <h4>Locale:</h4>
          <KendoDropDownList
            value={locale}
            onChange={handleLocaleChange}
            data={locales}
            textField="language"
            dataItemKey="locale"
          />
        </div>
        <div style={{ display: "flex", flexDirection: "column" }}>
          <h4>Orientation:</h4>
          <div style={{ display: "flex", gap: "0.5rem" }}>
            <input
              type="radio"
              name="orientation"
              id="horizontal"
              data-orientation="horizontal"
              className="k-radio k-radio-md"
              checked={orientation === "horizontal"}
              onChange={handleOrientationChange}
            />
            <label className="k-radio-label" htmlFor="horizontal">
              Horizontal
            </label>
            <br />
            <input
              type="radio"
              name="orientation"
              id="vertical"
              data-orientation="vertical"
              className="k-radio k-radio-md"
              checked={orientation === "vertical"}
              onChange={handleOrientationChange}
            />
            <label className="k-radio-label" htmlFor="vertical">
              Vertical
            </label>
          </div>
        </div>
      </div>
      <KendoLocalizationProvider language={locale.language}>
        <KendoIntlProvider locale={locale.locale}>
          <Scheduler
            data={data}
            onDataChange={handleDataChange}
            view={view}
            onViewChange={handleViewChange}
            date={date}
            onDateChange={handleDateChange}
            editable={true}
            timezone={timezone}
            modelFields={customModelFields}
            group={{
              resources: ["Rooms", "Persons"],
              orientation,
            }}
            resources={[
              {
                name: "Rooms",
                data: [
                  { text: "Meeting Room 101", value: 1 },
                  { text: "Meeting Room 201", value: 2, color: "#FF7272" },
                ],
                field: "RoomID",
                valueField: "value",
                textField: "text",
                colorField: "color",
              },
              {
                name: "Persons",
                data: [
                  { text: "Peter", value: 1, color: "#5392E4" },
                  { text: "Alex", value: 2, color: "#54677B" },
                ],
                field: "PersonIDs",
                valueField: "value",
                textField: "text",
                colorField: "color",
              },
            ]}
          >
            <KendoTimelineView />
            <KendoDayView />
            <KendoWeekView />
            <KendoMonthView />
            <KendoAgendaView />
          </Scheduler>
        </KendoIntlProvider>
      </KendoLocalizationProvider>
    </>
  );
};
