'use client';

import React, { FC, useEffect, useState } from 'react';
import { Modal, Button, message, Form, Input } from 'antd';
import { CloseOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { i18nText } from '../../i18nKeys';
import { ProfileData, ProfileRequest } from '../../types/profile';
import { PracticePersonData, PracticeDTO, PracticeData, PracticeCase } from '../../types/practice';
import { AUTH_TOKEN_KEY } from '../../constants/common';
import { useLocalStorage } from '../../hooks/useLocalStorage';
import { setPersonData, setPractice } from '../../actions/profile';
import { CustomInput } from '../view/CustomInput';
import { CustomMultiSelect } from '../view/CustomMultiSelect';
import { CustomSelect } from '../view/CustomSelect';
import { LinkButton } from '../view/LinkButton';

type EditExpertAboutModalProps = {
    open: boolean;
    handleCancel: () => void;
    locale: string;
    practice?: PracticeDTO;
    person?: ProfileData;
    refreshPractice: () => void;
    refreshPerson: () => void;
};

type FormPerson = PracticePersonData & {
    sessionLang: number[];
};

export const EditExpertAboutModal: FC<EditExpertAboutModalProps> = ({
    open,
    handleCancel,
    locale,
    practice,
    person,
    refreshPerson,
    refreshPractice
}) => {
    const [jwt] = useLocalStorage(AUTH_TOKEN_KEY, '');
    const [loading, setLoading] = useState<boolean>(false);
    const [form] = Form.useForm<FormPerson>();
    const [practiceCases, setPracticeCases] = useState<PracticeCase[]>([]);

    useEffect(() => {
        if (open) {
            if (practice?.person4Data) {
                form.setFieldsValue(practice.person4Data);

                setPracticeCases(practice.person4Data?.practiceCases || []);
            }
            if (person?.languagesLinks) {
                form.setFieldValue('sessionLang', person.languagesLinks.map(({ languageId }) => languageId))
            }
        }
    }, [open, practice?.person4Data]);

    const addPracticeCase = () => {
        setPracticeCases([
            ...practiceCases,
            {
                description: '',
                themesGroupIds: []
            }
        ]);
    };

    const deletePracticeCase = (index: number) => {
        setPracticeCases([...practiceCases].filter((cases, i) => i !== index));
    };

    const onChangePracticeDescription = (value: string, index: number) => {
        setPracticeCases(practiceCases.map((cases, i) => {
            if (i === index) {
                return {
                    ...cases,
                    description: value
                }
            }

            return cases;
        }));
    };

    const onChangePracticeThemes = (value: number[], index: number) => {
        setPracticeCases(practiceCases.map((cases, i) => {
            if (i === index) {
                return {
                    ...cases,
                    themesGroupIds: value
                }
            }

            return cases;
        }));
    };

    const onSave = () => {
        form.validateFields().then((values) => {
            const newPersonData: ProfileRequest = {
                login: person?.login,
                isPasswordKeepExisting: true,
                username: person?.username,
                surname: person?.surname,
                isFaceImageKeepExisting: true,
                phone: person?.phone,
                languagesLinks: values?.sessionLang?.map((id) => ({ languageId: +id })) || []
            };

            const newPracticeData: PracticeData = {
                practiceHours: values?.practiceHours,
                supervisionPerYearId: values?.supervisionPerYearId,
                sessionDuration: values?.sessionDuration ? (isNaN(Number(values.sessionDuration)) ? 0 : Number(values.sessionDuration)) : 0,
                sessionCost: values?.sessionCost ? (isNaN(Number(values.sessionCost)) ? 0 : Number(values.sessionCost)) : 0,
                practiceCases: practiceCases ? practiceCases : practice?.person4Data?.practiceCases
            }

            setLoading(true);
            Promise.all([
                setPractice(locale, jwt, newPracticeData),
                setPersonData(newPersonData, locale, jwt)
            ])
                .then(() => {
                    handleCancel();
                    refreshPractice();
                    refreshPerson();
                })
                .catch(() => {
                    message.error('Не удалось сохранить данные');
                })
                .finally(() => {
                    setLoading(false);
                })
        })
    };

    return (
        <Modal
            className="b-modal"
            open={open}
            title={undefined}
            onOk={undefined}
            onCancel={handleCancel}
            footer={false}
            width={498}
            closeIcon={<CloseOutlined style={{ fontSize: 20, color: '#000' }}/>}
        >
            <div className="b-modal__expert__content">
                <div className="b-modal__expert__title">{i18nText('aboutCoach', locale)}</div>
                <div className="b-modal__expert__inner">
                    <Form form={form} style={{ width: '100%', display: 'flex', gap: 16, flexDirection: 'column' }}>
                        <Form.Item
                            name="sessionLang"
                            noStyle
                        >
                            <CustomMultiSelect
                                label={i18nText('sessionLang', locale)}
                                options={person?.allLanguages?.map(({ id, nativeSpelling }) => ({ value: id, label: nativeSpelling })) || []}
                            />
                        </Form.Item>
                        <Form.Item
                            name="sessionDuration"
                            noStyle
                        >
                            <CustomInput
                                size="small"
                                placeholder={i18nText('sessionDuration', locale)}
                                autoComplete="off"
                                addonAfter={locale === 'ru' ? 'мин' : 'min'}
                            />
                        </Form.Item>
                        <Form.Item
                            name="sessionCost"
                            noStyle
                        >
                            <CustomSelect
                                label={i18nText('sessionCost', locale)}
                                options={practice?.person4Data?.sessionCosts?.map((cost) => ({ value: cost, label: cost })) || []}
                            />
                        </Form.Item>
                        <Form.Item
                            name="practiceHours"
                            noStyle
                        >
                            <CustomInput
                                size="small"
                                placeholder={i18nText('experienceHours', locale)}
                                autoComplete="off"
                                addonAfter={locale === 'ru' ? 'часов' : 'hours'}
                            />
                        </Form.Item>
                        <Form.Item
                            name="supervisionPerYearId"
                            noStyle
                        >
                            <CustomSelect
                                label={i18nText('supervisionCount', locale)}
                                options={practice?.person4Data?.supervisionPerYears?.map(({ id, name }) => ({ value: id, label: name })) || []}
                            />
                        </Form.Item>
                    </Form>
                </div>
                <div className="b-practice-cases">
                    <div className="b-practice-case__header">
                        <div>{i18nText('successfulCase', locale)}</div>
                        <LinkButton
                            type="link"
                            icon={<PlusOutlined />}
                            onClick={addPracticeCase}
                        />
                    </div>
                    {practiceCases.map(({ description, themesGroupIds }, index) => (
                        <div key={index} className="b-practice-case__item">
                            <div className="b-practice-case__content">
                                <div>
                                    <CustomMultiSelect
                                        value={themesGroupIds || []}
                                        label={i18nText('topics', locale)}
                                        options={practice?.person4Data?.themesGroups?.map(({ id, name }) => ({ value: id, label: name })) || []}
                                        onChange={(val) => onChangePracticeThemes(val, index)}
                                    />
                                </div>
                                <div>
                                    <Input.TextArea
                                        value={description}
                                        className="b-textarea"
                                        rows={2}
                                        placeholder={i18nText('description', locale)}
                                        onChange={(e) => onChangePracticeDescription(e.target.value, index)}
                                    />
                                </div>
                            </div>
                            <LinkButton
                                type="link"
                                danger
                                icon={<DeleteOutlined />}
                                onClick={() => deletePracticeCase(index)}
                            />
                        </div>
                    ))}
                </div>
                <div className="b-modal__expert__button">
                    <Button
                        className="card-detail__apply"
                        onClick={onSave}
                        loading={loading}
                    >
                        {i18nText('save', locale)}
                    </Button>
                </div>
            </div>
        </Modal>
    );
};
