import { faker } from '@faker-js/faker';
import React, { useState } from 'react';
import {
  Checkbox,
  CustomTags,
  Divider,
  FileUploadControl,
  Radio,
  ReadOnlyField,
  Select,
  SingleLineText,
  Tags,
} from '.';
import { generateItemArray } from '../../helpers/storybook';
import { TextButton } from '../Buttons';
import { DynamicListColumn } from '../DynamicDataList/DynamicDataList.model';
import {
  createInputRenderer,
  createSelectRenderer,
} from '../DynamicDataList/DynamicListDataEntry/Renderers';
import { formatDateTime } from '../Utils';
import { BooleanViewField } from './BooleanView/BooleanViewField';
import { DynamicDataListControl } from './DynamicDataListControl/DynamicDataListControl';
import { FileUpload } from './FileUploadControl/FileUploadControl';
import { TextArea } from './TextArea/TextArea';

interface DynamicListStoryData {
  position: number;
  id: number;
  locale: string;
  country: string;
}

function generateNames(amount: number): string[] {
  const users: string[] = [];
  for (let i = 1; i <= amount; i++) {
    const name = `${faker.name.firstName()} ${faker.name.lastName()}`;
    users.push(name);
  }
  return users;
}

function generateTitle(): string {
  const fakerTitle = faker.hacker.adjective().replace(/-/g, '');
  return fakerTitle.charAt(0).toUpperCase() + fakerTitle.slice(1);
}

const genresOptions = ['Crime', 'Drama', 'Thriller'];
const selectOptions = [
  { value: 'PG', label: 'PG' },
  { value: 'PG-13', label: 'PG-13' },
  { value: 'R', label: 'R' },
];

const dataListColumns: DynamicListColumn<DynamicListStoryData>[] = [
  {
    propertyName: 'id',
    label: 'Id',
    size: '50px',
  },
  {
    propertyName: 'locale',
    label: 'Locale',
    dataEntryRender: createInputRenderer({
      placeholder: 'Enter Locale',
    }),
  },
  {
    propertyName: 'country',
    label: 'Country',
    dataEntryRender: createSelectRenderer({
      options: [
        { value: 'Country 10', label: 'Country 10' },
        { value: 'Country 11', label: 'Country 11' },
        { value: 'Country 12', label: 'Country 12' },
      ],
      placeholder: 'Enter Country',
    }),
  },
];

export const SampleForm: React.FC = () => useCreateForm().form;
export const useCreateForm = (): {
  form: JSX.Element;
  title: string;
} => {
  const [id] = useState(faker.datatype.uuid());
  const [title, setTitle] = useState(`The ${generateTitle()}`);
  const [title2, setTitle2] = useState(`The ${generateTitle()}`);
  const [genres, setGenres] = useState<string[]>(['Crime', 'Drama']);
  const [ratings, setRatings] = useState<
    string | number | string[] | undefined
  >('R');
  const [shortDescription, setShortDescription] = useState('');
  const [longDescription, setLongDescription] = useState('');
  const [cast, setCast] = useState<string[]>(generateNames(2));
  const [status] = useState<boolean>(faker.datatype.boolean());
  const [createdTime] = useState<Date>(new Date());
  const [directors, setDirectors] = useState<string[]>(generateNames(3));
  const [locales, setLocales] = useState<string[]>(['en_US', 'pt_PT', 'zh_CN']);
  const [writers] = useState(generateNames(1)[0]);
  const [dataList, setDataList] = useState<DynamicListStoryData[]>(
    generateItemArray(4, (index) => ({
      position: index + 1,
      id: index,
      locale: faker.random.locale(),
      country: faker.address.country(),
    })),
  );
  const [radio, setRadio] = useState(1);
  const [check, setCheck] = useState<boolean>();
  const [file, setFile] = useState<FileUpload>();

  const [disabled, setDisabled] = useState<boolean>(false);

  return {
    form: (
      <>
        <div style={{ marginBottom: 10 }}>
          <TextButton
            onButtonClicked={() => setDisabled(!disabled)}
            text="Toggle Disabled"
          />
        </div>
        <Divider />
        <form
          style={{
            display: 'grid',
            gridAutoRows: 'max-content',
            gridTemplateColumns: '1fr',
            rowGap: '20px',
          }}
        >
          <ReadOnlyField label="Id" value={id} />
          <SingleLineText
            name="title"
            label="Title"
            value={title}
            disabled={disabled}
            onChange={(e) => setTitle(e.currentTarget.value)}
          />
          <ReadOnlyField label="Publish State" value="PUBLISHED" />
          <BooleanViewField
            label="Status"
            value={status}
            trueLabel="Enabled"
            falseLabel="Disabled"
          />
          <Tags
            name="genres"
            label="Genre(s)"
            value={genres}
            tagsOptions={genresOptions}
            onChange={(e) =>
              setGenres(e.currentTarget.value as unknown as string[])
            }
            disabled={disabled}
          />
          <Select
            name="ratings"
            label="Rating"
            value={ratings}
            options={selectOptions}
            onChange={(e) => setRatings(e.currentTarget.value)}
            disabled={disabled}
          />
          <SingleLineText
            name="shortDescription"
            label="Short Description"
            value={shortDescription}
            placeholder="Enter a short description..."
            onChange={(e) => setShortDescription(e.currentTarget.value)}
            disabled={disabled}
          />
          <TextArea
            name="longDescription"
            label="Long Description"
            value={longDescription}
            placeholder="Enter a description..."
            onChange={(e) => setLongDescription(e.currentTarget.value)}
            disabled={disabled}
          />
          <CustomTags
            name="cast"
            value={cast}
            label="Cast"
            onChange={(e) =>
              setCast(e.currentTarget.value as unknown as string[])
            }
            disabled={disabled}
          />
          <CustomTags
            name="directors"
            value={directors}
            label="Director(s)"
            onChange={(e) =>
              setDirectors(e.currentTarget.value as unknown as string[])
            }
            disabled={disabled}
          />
          <Tags
            name="locales"
            value={locales}
            label="Locale(s)"
            tagsOptions={['en_US', 'pt_PT', 'zh_CN']}
            onChange={(e) =>
              setLocales(e.currentTarget.value as unknown as string[])
            }
            disabled={disabled}
          />
          <DynamicDataListControl
            name={'dataList'}
            label={'Subtitles'}
            columns={dataListColumns}
            value={dataList}
            positionPropertyName={'position'}
            allowReordering={true}
            allowRowDragging={true}
            allowNewData={true}
            onChange={(e) => setDataList(e as DynamicListStoryData[])}
            disabled={disabled}
          />

          <Radio
            value={radio}
            onChange={(e) => setRadio(Number(e.currentTarget.value))}
            options={[
              { value: 1, label: 'A' },
              { value: 2, label: 'B' },
              { value: 3, label: 'C' },
            ]}
            name={'radio'}
            label={'Category'}
            disabled={disabled}
          />

          <Checkbox
            value={check}
            onChange={setCheck}
            name={'check'}
            label={'Is Premium?'}
            disabled={disabled}
          />

          <FileUploadControl
            name={'file'}
            value={file}
            onFileSelected={(file) => setFile(file)}
            placeholder={'Select a file'}
            label={'File'}
            disabled={disabled}
          />
          <ReadOnlyField
            label="Created At"
            value={createdTime.toISOString()}
            transform={formatDateTime}
          />
          <ReadOnlyField label="Writer(s)" value={writers} />
        </form>
      </>
    ),
    title,
  };
};
