import { InfoCircleOutlined } from "@ant-design/icons";
import { Form, Select, Switch, Table, Tag, Tooltip } from "antd";
import { useMemo } from "react";

import { getTcfDataRetentionTimeForPurpose } from "@devowl-wp/react-cookie-banner";

import { useFormTcfVendor } from "../../../../contexts/formTcfVendor.js";
import { useI18n } from "../../../../contexts/i18n.js";
import { FormHeadline } from "../../headline.js";
import { FormLayoutTcfVendor } from "../../layout.js";

import type { FormTcfVendorValueProps } from "../../../../types/formTcfVendor.js";
import type { FC } from "react";

const { Column } = Table;

const TABLE_FORM_ITEM_PROPS = {
    labelCol: { span: 0 },
    wrapperCol: { span: 24 },
    style: { margin: 0 },
};

const FORM_TCF_VENDOR_FIELD_PURPOSES_COLUMN_NAME_WIDTH = 250;

const FormTcfVendorFieldPurposes: FC = () => {
    const { __, _i, _n } = useI18n();

    const {
        vendor,
        declarations: { purposes, specialPurposes },
    } = useFormTcfVendor();
    const { dataRetention } = vendor;

    const usePurposes = useMemo(
        () =>
            Object.values(purposes)
                .map((purpose) =>
                    vendor.purposes.indexOf(purpose.id) > -1 || vendor.legIntPurposes.indexOf(purpose.id) > -1
                        ? { purpose, type: "normal" as "normal" | "special" }
                        : undefined,
                )
                .concat(
                    Object.values(specialPurposes).map((specialPurpose) =>
                        vendor.specialPurposes.indexOf(specialPurpose.id) > -1
                            ? { purpose: specialPurpose, type: "special" as "normal" | "special" }
                            : undefined,
                    ),
                )
                .filter(Boolean),
        [vendor, purposes, specialPurposes],
    );

    type TableRowType = (typeof usePurposes)[0];

    return (
        <>
            <FormHeadline
                offset={FormLayoutTcfVendor.labelCol.span}
                description={_i(
                    __(
                        'The vendor specifies for which defined purposes he wants to process (personal) data of your visitors and use cookies. These can be deselected if consent should not be obtained for certain purposes. The vendor specifies the legal basis for data processing in according to  {{aGdpr}}Art. 6 GDPR{{/aGdpr}} and whether you as the website operator can change this. "Legitimate Interest" means that this purpose is pre-selected on the basis of a legally designated legitimate interest, and the visitor to your website must actively object to it, if an objection is possible. "Consent" means that your visitors must explicitly agree to this purpose. The default settings are provided by the vendor, but do not have to match how you use the vendor on your website. In particular, you may need to make adjustments, if possible, in the "Legal basis" column. {{strong}}A legitimate interest exists only in a very few cases. If you are not sure, it is better to obtain consent.{{/strong}}',
                    ),
                    {
                        strong: <strong />,
                        aGdpr: (
                            <a href={__("https://gdpr-text.com/read/article-6/")} target="_blank" rel="noreferrer" />
                        ),
                    },
                )}
            >
                {__("Purposes and special purposes")}
            </FormHeadline>
            <Table<TableRowType>
                dataSource={usePurposes}
                rowKey={({ purpose: { id }, type }) => `${type}${id}`}
                size="small"
                bordered
                pagination={false}
                style={{ marginBottom: 25 }}
            >
                <Column<TableRowType>
                    width={FORM_TCF_VENDOR_FIELD_PURPOSES_COLUMN_NAME_WIDTH}
                    title={__("Name")}
                    dataIndex="name"
                    key="name"
                    render={(_, { purpose: { name } }) => name}
                />
                <Column<TableRowType>
                    title={__("Enabled")}
                    dataIndex="enabled"
                    key="enabled"
                    render={(_, { purpose: { id }, type }) => (
                        <Form.Item<FormTcfVendorValueProps>
                            {...TABLE_FORM_ITEM_PROPS}
                            name={
                                type === "special" ? undefined : ["restrictivePurposes", type, id.toString(), "enabled"]
                            }
                            valuePropName="checked"
                        >
                            <Switch
                                size="small"
                                disabled={type !== "normal"}
                                defaultChecked={type === "special" ? true : undefined}
                            />
                        </Form.Item>
                    )}
                />
                <Column<TableRowType>
                    title={__("Legal basis")}
                    dataIndex="name"
                    key="name"
                    render={(_, { purpose: { id }, type }) => (
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, nextValues) =>
                                prevValues.restrictivePurposes[type]?.[id].enabled !==
                                nextValues.restrictivePurposes[type]?.[id].enabled
                            }
                        >
                            {({ getFieldValue }) => (
                                <Form.Item
                                    {...TABLE_FORM_ITEM_PROPS}
                                    name={
                                        type === "special"
                                            ? undefined
                                            : ["restrictivePurposes", type, id.toString(), "legInt"]
                                    }
                                >
                                    <Select
                                        size="small"
                                        disabled={
                                            vendor.flexiblePurposes.indexOf(id) === -1 ||
                                            !getFieldValue(["restrictivePurposes", type, id.toString(), "enabled"])
                                        }
                                        defaultValue={type === "special" ? "no" : undefined}
                                    >
                                        <Select.Option value="yes">{__("Legitimate interest")}</Select.Option>
                                        <Select.Option value="no">{__("Consent")}</Select.Option>
                                    </Select>
                                </Form.Item>
                            )}
                        </Form.Item>
                    )}
                />
                <Column<TableRowType>
                    title={__("Description")}
                    dataIndex="description"
                    key="description"
                    render={(_, { purpose: { description, illustrations }, type }) => (
                        <Tooltip
                            title={
                                illustrations.length > 0 && (
                                    <div>
                                        <strong>{__("Illustrations")}: </strong>
                                        <ul>
                                            {illustrations.map((illustration) => (
                                                <li key={illustration}>{illustration}</li>
                                            ))}
                                        </ul>
                                    </div>
                                )
                            }
                            placement="bottomLeft"
                            overlayInnerStyle={{ width: 500 }}
                        >
                            <InfoCircleOutlined style={{ cursor: "pointer", opacity: 0.5 }} />
                            &nbsp;
                            {description} {type === "special" && <Tag color="warning">{__("Special purpose")}</Tag>}
                        </Tooltip>
                    )}
                />
                <Column<TableRowType>
                    title={__("Data retention period")}
                    dataIndex="dataRetention"
                    key="dataRetention"
                    render={(_, { purpose: { id }, type }) => {
                        const days = getTcfDataRetentionTimeForPurpose(dataRetention, id, type === "special");
                        return days ? _n("%d day", "%d days", days, days) : __("Not defined");
                    }}
                />
            </Table>
        </>
    );
};

export { FormTcfVendorFieldPurposes, FORM_TCF_VENDOR_FIELD_PURPOSES_COLUMN_NAME_WIDTH };
