import React, { Component, PropTypes } from 'react';
import cn from 'classnames';

import { reduxForm } from 'redux-form';
import * as BannersActions from 'core/actions/banners';

import UI from 'staff-legacy/components/ui';
import styles from 'staff-legacy/styles/banners/form';

const {
  Grid,
  Form, Form: { Input, Label, Group, Select, Static },
  Button,
} = UI;

const kinds = [
  {
    value: `jq`,
    label: `jqestate.ru`,
  }, {
    value: `rublevka`,
    label: `rublevka.ru`,
  }, {
    value: `riga`,
    label: `riga.ru`,
  }, {
    value: `minka`,
    label: `minka.ru`,
  }, {
    value: `kievka`,
    label: `kievka.ru`,
  },
];

const validate = (values) => {
  const errors = {};

  if (!values.kind) errors.kind = `Должен быть выбран сайт`;
  if (!values.title) errors.title = `Укажите заголовок`;
  if (!values.text) errors.text = `Укажите текст`;
  if (!values.targetUrl) errors.targetUrl = `Укажите ссылку`;

  return errors;
};

class BannerForm extends Component {
  static propTypes = {
    fields: PropTypes.object.isRequired,
    handleSubmit: PropTypes.func.isRequired,
    pristine: PropTypes.bool.isRequired,
    resetForm: PropTypes.func.isRequired,
  };

  add(values) {
    const { formKey, addBanner, updateBanner, resetForm } = this.props;

    if (formKey === `new`) {
      return addBanner(values).then(resetForm());
    } else {
      return updateBanner(formKey, values);
    }
  }

  delete() {
    const { formKey, removeBanner } = this.props;
    if (confirm(`Вы действительно хотите удалить баннер #${formKey}?`)) {
      return removeBanner(formKey);
    }
  }

  render() {
    const {
      fields,
      handleSubmit,
      pristine,
      formKey,
      values,
    } = this.props;

    return (
      <Form.Container onSubmit={handleSubmit}>
        <Grid.Row>
          <Grid.Col xs="12">
            <h4>
              {formKey === `new` && `Добавить баннер`}
              {formKey !== `new` && `Баннер #${formKey} на сайте ${values.kind}`}
            </h4>
          </Grid.Col>
        </Grid.Row>

        <Group horizontal kind={cn({ error: (fields.kind.touched && !!fields.kind.error) })}>
          <Grid.Row>
            <Grid.Col sm="2" className={styles.textRight}>
              <Label htmlFor="kind">Сайт</Label>
            </Grid.Col>
            <Grid.Col sm="4">
              <Select id="kind" placeholder="Сайт" options={kinds} {...fields.kind} block />
            </Grid.Col>

            {fields.kind.touched && fields.kind.error && <Grid.Col sm="4"><Form.Static>{fields.kind.error}</Form.Static></Grid.Col>}
          </Grid.Row>
        </Group>

        <Group horizontal kind={cn({ error: (fields.title.touched && !!fields.title.error) })}>
          <Grid.Row>
            <Grid.Col sm="2" className={styles.textRight}>
              <Label htmlFor="title">Заголовок</Label>
            </Grid.Col>
            <Grid.Col sm="4">
              <Input block id="title" {...fields.title} />
            </Grid.Col>

            {fields.title.touched && fields.title.error && <Grid.Col sm="4"><Form.Static>{fields.title.error}</Form.Static></Grid.Col>}
          </Grid.Row>
        </Group>

        <Group horizontal kind={cn({ error: (fields.text.touched && !!fields.text.error) })}>
          <Grid.Row>
            <Grid.Col sm="2" className={styles.textRight}>
              <Label htmlFor="text">Текст</Label>
            </Grid.Col>
            <Grid.Col sm="4">
              <Input block id="text" {...fields.text} />
            </Grid.Col>

            {fields.text.touched && fields.text.error && <Grid.Col sm="4"><Form.Static>{fields.text.error}</Form.Static></Grid.Col>}
          </Grid.Row>
        </Group>

        <Group horizontal kind={cn({ error: (fields.targetUrl.touched && !!fields.targetUrl.error) })}>
          <Grid.Row>
            <Grid.Col sm="2" className={styles.textRight}>
              <Label htmlFor="targetUrl">Ссылка</Label>
            </Grid.Col>
            <Grid.Col sm="4">
              <Input block id="targetUrl" {...fields.targetUrl} />
            </Grid.Col>

            {fields.targetUrl.touched && fields.targetUrl.error && <Grid.Col sm="4"><Form.Static>{fields.targetUrl.error}</Form.Static></Grid.Col>}
          </Grid.Row>
        </Group>

        {values.kind === `jq` &&
          <Group horizontal>
            <Grid.Row>
              <Grid.Col sm="2" className={styles.textRight}>
                <Label htmlFor="image">Фотография</Label>
              </Grid.Col>
              <Grid.Col sm="4">
                {fields.image.defaultValue && <p>Загружена (<a href={fields.image.defaultValue.url} target="_blank">{fields.image.defaultValue.id}</a>), но можно добавить новую:</p>}
                {!fields.image.defaultValue && <p>Фотографии нет, надо загрузить</p>}
                <Input type="file" block id="image" {...fields.image} value={null} />
              </Grid.Col>
            </Grid.Row>
          </Group>
        }

        {values.kind && values.kind !== `jq` &&
          <Group horizontal>
            <Grid.Row>
              <Grid.Col sm="2" className={styles.textRight}>
                <Label htmlFor="brokerId">ID брокера</Label>
              </Grid.Col>
              <Grid.Col sm="4">
                <Input block id="brokerId" {...fields.brokerId} />
              </Grid.Col>
            </Grid.Row>
          </Group>
        }

        {values.kind && values.kind !== `jq` &&
          <Group horizontal>
            <Grid.Row>
              <Grid.Col sm="2" className={styles.textRight}>
                <Label htmlFor="color">Цвет текста</Label>
              </Grid.Col>
              <Grid.Col sm="4">
                <Input block id="color" {...fields.color} />
              </Grid.Col>
            </Grid.Row>
          </Group>
        }

        {values.kind && values.kind !== `jq` &&
          <Group horizontal>
            <Grid.Row>
              <Grid.Col sm="2" className={styles.textRight}>
                <Label htmlFor="backgroundColor">Цвет фона</Label>
              </Grid.Col>
              <Grid.Col sm="4">
                <Input block id="backgroundColor" {...fields.backgroundColor} />
              </Grid.Col>
            </Grid.Row>
          </Group>
        }

        <Group horizontal>
          <Grid.Row>
            <Grid.Col sm="2" smOffset="2">
              {formKey === `new` && <Button kind="success" size="sm" disabled={pristine} onClick={handleSubmit(::this.add)}>Добавить</Button>}
              {formKey !== `new` && <Button kind="primary" size="sm" disabled={pristine} onClick={handleSubmit(::this.add)}>Сохранить</Button>}
            </Grid.Col>
            <Grid.Col sm="2" className={styles.textRight}>
              {formKey !== `new` && <Button kind="danger" size="sm" onClick={handleSubmit(::this.delete)}>Удалить</Button>}
            </Grid.Col>
          </Grid.Row>
        </Group>
      </Form.Container>
    );
  }
}

export const formFields = [
  `kind`,
  `title`,
  `text`,
  `targetUrl`,
  `brokerId`,
  `image`,
  `styleProperties`,
  `color`,
  `backgroundColor`,
];

const formSettings = {
  form: `banner`,
  fields: formFields,
  validate,
};

const actions = {
  addBanner: BannersActions.addBanner,
  updateBanner: BannersActions.updateBanner,
  removeBanner: BannersActions.removeBanner,
  addBannerImage: BannersActions.addBannerImage,
};

export default reduxForm(formSettings, () => {}, actions)(BannerForm);
