import ClientLayout from '@/Layouts/ClientLayout';
import { Head, router, usePage } from '@inertiajs/react';
import axios from 'axios';
import {
    CheckCircle2,
    CirclePause,
    CirclePlay,
    FileSpreadsheet,
    Link2,
    Loader2,
    Play,
    Plus,
    Save,
    Trash2,
    Unplug,
    X,
    Zap,
} from 'lucide-react';
import { useMemo, useState } from 'react';

const inputClass =
    'w-full rounded-xl border border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900 px-3 py-2.5 text-sm text-neutral-900 dark:text-neutral-100 focus:outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500';

const cardClass =
    'rounded-2xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 shadow-sm';

const triggerLabels = {
    new_row: 'New Row Added',
    column_changed: 'Column Value Changed',
    conditions: 'Conditions Match',
    new_row_conditions: 'New Row + Conditions',
    manual: 'Manual / Send Now Only',
};

const operatorLabels = {
    equals: 'Equals',
    not_equals: 'Not Equals',
    contains: 'Contains',
    not_contains: 'Does Not Contain',
    is_empty: 'Is Empty',
    is_not_empty: 'Is Not Empty',
    starts_with: 'Starts With',
    ends_with: 'Ends With',
    greater_than: 'Greater Than',
    less_than: 'Less Than',
};

function extractSpreadsheetId(value) {
    const text = String(value || '').trim();
    const match = text.match(
        /\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/
    );

    if (match?.[1]) return match[1];
    if (/^[a-zA-Z0-9-_]{20,}$/.test(text)) return text;
    return '';
}

function niceDate(value) {
    if (!value) return 'Never';

    try {
        return new Date(value).toLocaleString();
    } catch {
        return value;
    }
}

function conditionNeedsValue(operator) {
    return !['is_empty', 'is_not_empty'].includes(operator);
}

function conditionText(condition) {
    const label =
        operatorLabels[condition?.operator] ||
        condition?.operator ||
        'Equals';

    const value = conditionNeedsValue(condition?.operator)
        ? ` ${condition?.value ?? ''}`
        : '';

    return `${condition?.column || 'Column'} ${label}${value}`;
}

function triggerSummary(item) {
    const type = item.trigger_type || 'conditions';

    if (type === 'column_changed') {
        const target = item.watch_value
            ? ` → ${item.watch_value}`
            : '';
        return `${triggerLabels[type]}: ${item.watch_column || 'Column'}${target}`;
    }

    if (type === 'new_row') {
        return triggerLabels[type];
    }

    if (type === 'manual') {
        return triggerLabels[type];
    }

    const count = Array.isArray(item.conditions)
        ? item.conditions.length
        : 0;

    return count
        ? `${triggerLabels[type]} · ${count} condition${count === 1 ? '' : 's'}`
        : triggerLabels[type];
}

export default function GoogleSheetsIndex({
    googleReady = false,
    callbackUrl = '',
    connection = null,
    whatsappAccounts = [],
    templates = [],
    automations = [],
}) {
    const { flash = {}, errors = {} } = usePage().props;

    const [sheetLink, setSheetLink] = useState('');
    const [spreadsheetId, setSpreadsheetId] = useState('');
    const [spreadsheetTitle, setSpreadsheetTitle] = useState('');
    const [tabs, setTabs] = useState([]);
    const [sheetName, setSheetName] = useState('');
    const [headers, setHeaders] = useState([]);
    const [loading, setLoading] = useState(false);
    const [message, setMessage] = useState('');

    const [automationName, setAutomationName] =
        useState('Google Sheet WhatsApp');
    const [accountId, setAccountId] = useState('');
    const [templateId, setTemplateId] = useState('');
    const [phoneColumn, setPhoneColumn] = useState('');
    const [nameColumn, setNameColumn] = useState('');
    const [countryCode, setCountryCode] = useState('91');
    const [mapping, setMapping] = useState({});

    const [triggerType, setTriggerType] =
        useState('conditions');
    const [conditionMatch, setConditionMatch] =
        useState('all');
    const [conditions, setConditions] = useState([]);
    const [watchColumn, setWatchColumn] = useState('');
    const [watchValue, setWatchValue] = useState('');

    const selectedAccount = useMemo(
        () =>
            whatsappAccounts.find(
                (a) =>
                    String(a.id) ===
                    String(accountId)
            ),
        [accountId, whatsappAccounts]
    );

    const accountTemplates = useMemo(() => {
        if (!selectedAccount) return [];

        return templates.filter(
            (t) =>
                !t.waba_id ||
                !selectedAccount.waba_id ||
                String(t.waba_id) ===
                    String(selectedAccount.waba_id)
        );
    }, [selectedAccount, templates]);

    const selectedTemplate = useMemo(
        () =>
            accountTemplates.find(
                (t) =>
                    String(t.id) ===
                    String(templateId)
            ),
        [accountTemplates, templateId]
    );

    const variableCount = Number(
        selectedTemplate?.body_variable_count || 0
    );

    async function loadSheet() {
        const id = extractSpreadsheetId(sheetLink);

        setMessage('');
        setTabs([]);
        setHeaders([]);
        setSheetName('');

        if (!id) {
            setMessage(
                'Paste a valid Google Sheet link or Spreadsheet ID.'
            );
            return;
        }

        setSpreadsheetId(id);
        setLoading(true);

        try {
            const { data } = await axios.get(
                route(
                    'client.google-sheets.sheets',
                    id
                )
            );

            setSpreadsheetTitle(
                data?.title || ''
            );

            setTabs(
                data?.sheets || []
            );
        } catch (error) {
            setMessage(
                error?.response?.data?.message ||
                    'Could not open this Google Sheet. Make sure the connected Google account has access.'
            );
        } finally {
            setLoading(false);
        }
    }

    async function chooseTab(name) {
        setSheetName(name);
        setHeaders([]);
        setPhoneColumn('');
        setNameColumn('');
        setMapping({});
        setWatchColumn('');
        setWatchValue('');
        setConditions([]);
        setMessage('');

        if (!spreadsheetId || !name) return;

        setLoading(true);

        try {
            const { data } = await axios.get(
                route(
                    'client.google-sheets.headers',
                    spreadsheetId
                ),
                {
                    params: {
                        sheet: name,
                    },
                }
            );

            const found = (
                data?.headers || []
            ).filter(Boolean);

            setHeaders(found);

            const guess = (names) =>
                found.find((h) =>
                    names.includes(
                        String(h)
                            .trim()
                            .toLowerCase()
                    )
                ) || '';

            const phoneGuess = guess([
                'mobile',
                'phone',
                'phone number',
                'whatsapp',
                'whatsapp number',
            ]);

            const nameGuess = guess([
                'name',
                'full name',
                'customer name',
                'contact name',
            ]);

            const sendGuess = guess([
                'send',
                'send whatsapp',
                'whatsapp send',
                'trigger',
            ]);

            setPhoneColumn(phoneGuess);
            setNameColumn(nameGuess);

            if (sendGuess) {
                setConditions([
                    {
                        column: sendGuess,
                        operator: 'equals',
                        value: 'YES',
                    },
                ]);
            }
        } catch (error) {
            setMessage(
                error?.response?.data?.message ||
                    'Could not read columns from row 1.'
            );
        } finally {
            setLoading(false);
        }
    }

    function chooseTemplate(value) {
        setTemplateId(value);
        setMapping({});
    }

    function addCondition() {
        setConditions((old) => [
            ...old,
            {
                column: '',
                operator: 'equals',
                value: '',
            },
        ]);
    }

    function updateCondition(
        index,
        key,
        value
    ) {
        setConditions((old) =>
            old.map((condition, idx) =>
                idx === index
                    ? {
                          ...condition,
                          [key]: value,
                      }
                    : condition
            )
        );
    }

    function removeCondition(index) {
        setConditions((old) =>
            old.filter(
                (_, idx) => idx !== index
            )
        );
    }

    function saveAutomation(active = true) {
        setMessage('');

        if (
            !spreadsheetId ||
            !sheetName ||
            !headers.length
        ) {
            setMessage(
                'Load a Google Sheet and select its tab first.'
            );
            return;
        }

        if (
            !accountId ||
            !templateId ||
            !phoneColumn
        ) {
            setMessage(
                'Select WhatsApp number, template and phone column.'
            );
            return;
        }

        for (
            let i = 1;
            i <= variableCount;
            i += 1
        ) {
            if (!mapping[String(i)]) {
                setMessage(
                    `Map template variable {{${i}}}.`
                );
                return;
            }
        }

        if (
            triggerType ===
                'column_changed' &&
            !watchColumn
        ) {
            setMessage(
                'Select the column to watch for changes.'
            );
            return;
        }

        if (
            ['conditions', 'new_row_conditions'].includes(
                triggerType
            ) &&
            conditions.length === 0
        ) {
            setMessage(
                'Add at least one condition.'
            );
            return;
        }

        for (const condition of conditions) {
            if (!condition.column) {
                setMessage(
                    'Select a column for every condition.'
                );
                return;
            }

            if (
                conditionNeedsValue(
                    condition.operator
                ) &&
                String(
                    condition.value || ''
                ).trim() === ''
            ) {
                setMessage(
                    `Enter a value for ${condition.column}.`
                );
                return;
            }
        }

        router.post(
            route(
                'client.google-sheets.automations.store'
            ),
            {
                name: automationName,
                spreadsheet_id: spreadsheetId,
                spreadsheet_title:
                    spreadsheetTitle,
                sheet_name: sheetName,
                channel_account_id: accountId,
                whatsapp_template_id: templateId,
                phone_column: phoneColumn,
                name_column:
                    nameColumn || null,
                variable_mapping: mapping,
                trigger_type: triggerType,
                condition_match:
                    conditionMatch,
                conditions,
                watch_column:
                    watchColumn || null,
                watch_value:
                    watchValue || null,
                default_country_code:
                    countryCode,
                active,
            },
            {
                preserveScroll: true,
            }
        );
    }

    const allError =
        flash.error ||
        message ||
        Object.values(errors || {})[0];

    const showConditions = [
        'conditions',
        'new_row_conditions',
        'column_changed',
        'manual',
    ].includes(triggerType);

    return (
        <ClientLayout>
            <Head title="Google Sheets" />

            <div className="mx-auto max-w-7xl space-y-6 p-4 sm:p-6">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
                    <div>
                        <div className="flex items-center gap-2">
                            <FileSpreadsheet className="h-7 w-7 text-emerald-600" />
                            <h1 className="text-2xl font-semibold text-neutral-900 dark:text-white">
                                Google Sheets → WhatsApp
                            </h1>
                        </div>

                        <p className="mt-1 text-sm text-neutral-500">
                            Connect your own Google account, map Sheet columns to an approved WhatsApp template, and automate messages with advanced triggers.
                        </p>
                    </div>

                    <div className="flex flex-wrap items-center gap-2">
                        <a
                            href={route(
                                'client.google-sheets.lookup-bots.index'
                            )}
                            className="inline-flex items-center rounded-xl border border-emerald-200 bg-white px-3 py-2 text-xs font-medium text-emerald-700 hover:bg-emerald-50 dark:border-emerald-900/50 dark:bg-neutral-900 dark:text-emerald-300"
                        >
                            Lookup Bots
                        </a>

                        <div className="rounded-full bg-emerald-50 px-3 py-1.5 text-xs font-medium text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300">
                            Phase 3 · Advanced Trigger Engine
                        </div>
                    </div>
                </div>

                {(flash.success ||
                    allError) && (
                    <div
                        className={`rounded-xl border px-4 py-3 text-sm ${
                            allError
                                ? 'border-red-200 bg-red-50 text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-300'
                                : 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/50 dark:bg-emerald-950/30 dark:text-emerald-300'
                        }`}
                    >
                        {allError ||
                            flash.success}
                    </div>
                )}

                {!googleReady ? (
                    <div
                        className={`${cardClass} p-6`}
                    >
                        <h2 className="font-semibold text-neutral-900 dark:text-white">
                            Google OAuth setup required
                        </h2>

                        <p className="mt-2 text-sm text-neutral-500">
                            Admin only: configure Google Workspace OAuth Client ID and Client Secret in Admin → Integrations.
                        </p>

                        <div className="mt-4 text-xs font-medium text-neutral-600 dark:text-neutral-300">
                            Authorized redirect URI
                        </div>

                        <code className="mt-1 block overflow-x-auto rounded-xl bg-neutral-100 p-3 text-xs dark:bg-neutral-950">
                            {callbackUrl}
                        </code>
                    </div>
                ) : !connection ? (
                    <div
                        className={`${cardClass} p-10 text-center`}
                    >
                        <FileSpreadsheet className="mx-auto h-14 w-14 text-emerald-600" />

                        <h2 className="mt-4 text-xl font-semibold text-neutral-900 dark:text-white">
                            Connect Your Google Account
                        </h2>

                        <p className="mx-auto mt-2 max-w-2xl text-sm text-neutral-500">
                            Each i-Touch Digital Service workspace connects its own Google account. Your Google token is stored encrypted and is never shared with another client.
                        </p>

                        <a
                            href={route(
                                'client.google-sheets.oauth.redirect'
                            )}
                            className="mt-6 inline-flex rounded-xl bg-emerald-600 px-6 py-3 text-sm font-medium text-white hover:bg-emerald-700"
                        >
                            Connect Google Account
                        </a>
                    </div>
                ) : (
                    <>
                        <div
                            className={`${cardClass} p-5`}
                        >
                            <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                                <div className="flex items-center gap-3">
                                    {connection.picture_url ? (
                                        <img
                                            src={
                                                connection.picture_url
                                            }
                                            alt=""
                                            className="h-11 w-11 rounded-full"
                                        />
                                    ) : (
                                        <CheckCircle2 className="h-11 w-11 text-emerald-600" />
                                    )}

                                    <div>
                                        <div className="font-medium text-neutral-900 dark:text-white">
                                            {connection.name ||
                                                'Google Account'}
                                        </div>

                                        <div className="text-xs text-neutral-500">
                                            {
                                                connection.email
                                            }{' '}
                                            · Connected
                                        </div>
                                    </div>
                                </div>

                                <button
                                    type="button"
                                    onClick={() =>
                                        router.delete(
                                            route(
                                                'client.google-sheets.disconnect'
                                            )
                                        )
                                    }
                                    className="inline-flex items-center gap-2 rounded-xl border border-red-200 px-3 py-2 text-sm text-red-600 dark:border-red-900/50"
                                >
                                    <Unplug className="h-4 w-4" />
                                    Disconnect
                                </button>
                            </div>
                        </div>

                        <div
                            className={`${cardClass} p-5`}
                        >
                            <div className="flex items-center gap-2">
                                <Link2 className="h-5 w-5 text-emerald-600" />

                                <h2 className="font-semibold text-neutral-900 dark:text-white">
                                    1. Select Google Sheet
                                </h2>
                            </div>

                            <p className="mt-1 text-sm text-neutral-500">
                                Paste a Sheet link. i-Touch Digital Service detects tabs and columns from row 1.
                            </p>

                            <div className="mt-5 flex flex-col gap-3 sm:flex-row">
                                <input
                                    className={
                                        inputClass
                                    }
                                    value={
                                        sheetLink
                                    }
                                    onChange={(e) =>
                                        setSheetLink(
                                            e.target
                                                .value
                                        )
                                    }
                                    placeholder="https://docs.google.com/spreadsheets/d/..."
                                />

                                <button
                                    type="button"
                                    onClick={
                                        loadSheet
                                    }
                                    disabled={
                                        loading
                                    }
                                    className="inline-flex shrink-0 items-center justify-center gap-2 rounded-xl bg-emerald-600 px-5 py-2.5 text-sm font-medium text-white disabled:opacity-60"
                                >
                                    {loading && (
                                        <Loader2 className="h-4 w-4 animate-spin" />
                                    )}
                                    Load Sheet
                                </button>
                            </div>

                            {tabs.length >
                                0 && (
                                <div className="mt-5">
                                    <label className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                        {spreadsheetTitle ||
                                            'Spreadsheet'}{' '}
                                        · Sheet / Tab
                                    </label>

                                    <select
                                        className={`${inputClass} mt-1.5`}
                                        value={
                                            sheetName
                                        }
                                        onChange={(
                                            e
                                        ) =>
                                            chooseTab(
                                                e
                                                    .target
                                                    .value
                                            )
                                        }
                                    >
                                        <option value="">
                                            Select
                                            Sheet /
                                            Tab
                                        </option>

                                        {tabs.map(
                                            (
                                                tab
                                            ) => (
                                                <option
                                                    key={
                                                        tab.id
                                                    }
                                                    value={
                                                        tab.title
                                                    }
                                                >
                                                    {
                                                        tab.title
                                                    }
                                                </option>
                                            )
                                        )}
                                    </select>
                                </div>
                            )}

                            {headers.length >
                                0 && (
                                <div className="mt-5">
                                    <div className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                        Detected
                                        Columns
                                    </div>

                                    <div className="mt-2 flex flex-wrap gap-2">
                                        {headers.map(
                                            (
                                                header
                                            ) => (
                                                <span
                                                    key={
                                                        header
                                                    }
                                                    className="rounded-full bg-neutral-100 px-3 py-1.5 text-xs text-neutral-700 dark:bg-neutral-800 dark:text-neutral-200"
                                                >
                                                    {
                                                        header
                                                    }
                                                </span>
                                            )
                                        )}
                                    </div>
                                </div>
                            )}
                        </div>

                        {headers.length >
                            0 && (
                            <div
                                className={`${cardClass} p-5`}
                            >
                                <div className="flex items-center gap-2">
                                    <Zap className="h-5 w-5 text-emerald-600" />

                                    <h2 className="font-semibold text-neutral-900 dark:text-white">
                                        2. WhatsApp Template & Variable Mapping
                                    </h2>
                                </div>

                                <div className="mt-5 grid gap-4 md:grid-cols-2">
                                    <label>
                                        <span className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                            Automation
                                            Name
                                        </span>

                                        <input
                                            className={`${inputClass} mt-1.5`}
                                            value={
                                                automationName
                                            }
                                            onChange={(
                                                e
                                            ) =>
                                                setAutomationName(
                                                    e
                                                        .target
                                                        .value
                                                )
                                            }
                                        />
                                    </label>

                                    <label>
                                        <span className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                            WhatsApp
                                            Number
                                        </span>

                                        <select
                                            className={`${inputClass} mt-1.5`}
                                            value={
                                                accountId
                                            }
                                            onChange={(
                                                e
                                            ) => {
                                                setAccountId(
                                                    e
                                                        .target
                                                        .value
                                                );
                                                setTemplateId(
                                                    ''
                                                );
                                                setMapping(
                                                    {}
                                                );
                                            }}
                                        >
                                            <option value="">
                                                Select
                                                connected
                                                WhatsApp
                                                number
                                            </option>

                                            {whatsappAccounts.map(
                                                (
                                                    account
                                                ) => (
                                                    <option
                                                        key={
                                                            account.id
                                                        }
                                                        value={
                                                            account.id
                                                        }
                                                    >
                                                        {account.display_name ||
                                                            account.phone_number_id}{' '}
                                                        ·{' '}
                                                        {
                                                            account.phone_number_id
                                                        }
                                                    </option>
                                                )
                                            )}
                                        </select>
                                    </label>

                                    <label>
                                        <span className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                            Approved
                                            WhatsApp
                                            Template
                                        </span>

                                        <select
                                            className={`${inputClass} mt-1.5`}
                                            value={
                                                templateId
                                            }
                                            onChange={(
                                                e
                                            ) =>
                                                chooseTemplate(
                                                    e
                                                        .target
                                                        .value
                                                )
                                            }
                                            disabled={
                                                !accountId
                                            }
                                        >
                                            <option value="">
                                                Select
                                                approved
                                                template
                                            </option>

                                            {accountTemplates.map(
                                                (
                                                    template
                                                ) => (
                                                    <option
                                                        key={
                                                            template.id
                                                        }
                                                        value={
                                                            template.id
                                                        }
                                                        disabled={
                                                            template.sheet_sender_supported ===
                                                            false
                                                        }
                                                    >
                                                        {
                                                            template.name
                                                        }{' '}
                                                        ·{' '}
                                                        {
                                                            template.language
                                                        }
                                                        {template.sheet_sender_supported ===
                                                        false
                                                            ? ' · unsupported header/button variables'
                                                            : ''}
                                                    </option>
                                                )
                                            )}
                                        </select>
                                    </label>

                                    <label>
                                        <span className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                            Phone
                                            Number
                                            Column
                                        </span>

                                        <select
                                            className={`${inputClass} mt-1.5`}
                                            value={
                                                phoneColumn
                                            }
                                            onChange={(
                                                e
                                            ) =>
                                                setPhoneColumn(
                                                    e
                                                        .target
                                                        .value
                                                )
                                            }
                                        >
                                            <option value="">
                                                Select
                                                phone/mobile
                                                column
                                            </option>

                                            {headers.map(
                                                (
                                                    h
                                                ) => (
                                                    <option
                                                        key={
                                                            h
                                                        }
                                                        value={
                                                            h
                                                        }
                                                    >
                                                        {
                                                            h
                                                        }
                                                    </option>
                                                )
                                            )}
                                        </select>
                                    </label>

                                    <label>
                                        <span className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                            Contact
                                            Name Column
                                            (optional)
                                        </span>

                                        <select
                                            className={`${inputClass} mt-1.5`}
                                            value={
                                                nameColumn
                                            }
                                            onChange={(
                                                e
                                            ) =>
                                                setNameColumn(
                                                    e
                                                        .target
                                                        .value
                                                )
                                            }
                                        >
                                            <option value="">
                                                No name
                                                column
                                            </option>

                                            {headers.map(
                                                (
                                                    h
                                                ) => (
                                                    <option
                                                        key={
                                                            h
                                                        }
                                                        value={
                                                            h
                                                        }
                                                    >
                                                        {
                                                            h
                                                        }
                                                    </option>
                                                )
                                            )}
                                        </select>
                                    </label>

                                    <label>
                                        <span className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                            Default
                                            Country
                                            Code
                                        </span>

                                        <input
                                            className={`${inputClass} mt-1.5`}
                                            value={
                                                countryCode
                                            }
                                            onChange={(
                                                e
                                            ) =>
                                                setCountryCode(
                                                    e.target.value.replace(
                                                        /\D/g,
                                                        ''
                                                    )
                                                )
                                            }
                                            placeholder="91"
                                        />

                                        <span className="mt-1 block text-[11px] text-neutral-400">
                                            Used only
                                            when Sheet
                                            has a local
                                            number
                                            without
                                            country
                                            code.
                                        </span>
                                    </label>
                                </div>

                                {selectedTemplate && (
                                    <div className="mt-5 rounded-xl border border-neutral-200 bg-neutral-50 p-4 dark:border-neutral-800 dark:bg-neutral-950/50">
                                        <div className="text-xs font-semibold uppercase tracking-wide text-neutral-500">
                                            Template
                                            Preview
                                        </div>

                                        <div className="mt-2 whitespace-pre-wrap text-sm text-neutral-800 dark:text-neutral-200">
                                            {selectedTemplate.body_text ||
                                                'Template has no text body.'}
                                        </div>

                                        {variableCount >
                                            0 && (
                                            <div className="mt-5 space-y-3">
                                                <div className="text-sm font-medium text-neutral-900 dark:text-white">
                                                    Map
                                                    Template
                                                    Variables
                                                </div>

                                                {Array.from(
                                                    {
                                                        length: variableCount,
                                                    },
                                                    (
                                                        _,
                                                        idx
                                                    ) =>
                                                        idx +
                                                        1
                                                ).map(
                                                    (
                                                        n
                                                    ) => (
                                                        <div
                                                            key={
                                                                n
                                                            }
                                                            className="grid items-center gap-3 sm:grid-cols-[100px_1fr]"
                                                        >
                                                            <code className="rounded-lg bg-white px-3 py-2 text-center text-sm dark:bg-neutral-900">
                                                                {`{{${n}}}`}
                                                            </code>

                                                            <select
                                                                className={
                                                                    inputClass
                                                                }
                                                                value={
                                                                    mapping[
                                                                        String(
                                                                            n
                                                                        )
                                                                    ] ||
                                                                    ''
                                                                }
                                                                onChange={(
                                                                    e
                                                                ) =>
                                                                    setMapping(
                                                                        (
                                                                            old
                                                                        ) => ({
                                                                            ...old,
                                                                            [String(
                                                                                n
                                                                            )]:
                                                                                e
                                                                                    .target
                                                                                    .value,
                                                                        })
                                                                    )
                                                                }
                                                            >
                                                                <option value="">
                                                                    Select
                                                                    Sheet
                                                                    column
                                                                </option>

                                                                {headers.map(
                                                                    (
                                                                        h
                                                                    ) => (
                                                                        <option
                                                                            key={
                                                                                h
                                                                            }
                                                                            value={
                                                                                h
                                                                            }
                                                                        >
                                                                            {
                                                                                h
                                                                            }
                                                                        </option>
                                                                    )
                                                                )}
                                                            </select>
                                                        </div>
                                                    )
                                                )}
                                            </div>
                                        )}
                                    </div>
                                )}

                                <div className="mt-6 border-t border-neutral-200 pt-5 dark:border-neutral-800">
                                    <h3 className="text-sm font-semibold text-neutral-900 dark:text-white">
                                        3. Trigger
                                        & Conditions
                                    </h3>

                                    <p className="mt-1 text-xs text-neutral-500">
                                        Choose how rows become eligible for WhatsApp sending. Automatic triggers are checked every minute; Send Now checks immediately.
                                    </p>

                                    <div className="mt-4 grid gap-4 md:grid-cols-2">
                                        <label>
                                            <span className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                                Trigger
                                                Type
                                            </span>

                                            <select
                                                className={`${inputClass} mt-1.5`}
                                                value={
                                                    triggerType
                                                }
                                                onChange={(
                                                    e
                                                ) => {
                                                    setTriggerType(
                                                        e
                                                            .target
                                                            .value
                                                    );
                                                    setWatchColumn(
                                                        ''
                                                    );
                                                    setWatchValue(
                                                        ''
                                                    );
                                                }}
                                            >
                                                <option value="new_row">
                                                    New
                                                    Row
                                                    Added
                                                </option>
                                                <option value="column_changed">
                                                    Column
                                                    Value
                                                    Changed
                                                </option>
                                                <option value="conditions">
                                                    Conditions
                                                    Match
                                                </option>
                                                <option value="new_row_conditions">
                                                    New
                                                    Row +
                                                    Conditions
                                                </option>
                                                <option value="manual">
                                                    Manual
                                                    /
                                                    Send
                                                    Now
                                                    Only
                                                </option>
                                            </select>
                                        </label>

                                        {showConditions && (
                                            <label>
                                                <span className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                                    Match
                                                    Conditions
                                                </span>

                                                <select
                                                    className={`${inputClass} mt-1.5`}
                                                    value={
                                                        conditionMatch
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        setConditionMatch(
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                >
                                                    <option value="all">
                                                        ALL
                                                        conditions
                                                    </option>
                                                    <option value="any">
                                                        ANY
                                                        condition
                                                    </option>
                                                </select>
                                            </label>
                                        )}
                                    </div>

                                    {triggerType ===
                                        'new_row' && (
                                        <div className="mt-4 rounded-xl bg-blue-50 p-4 text-xs text-blue-800 dark:bg-blue-950/30 dark:text-blue-200">
                                            Existing rows are used as the baseline when you activate this automation. Only rows added below that baseline are eligible automatically.
                                        </div>
                                    )}

                                    {triggerType ===
                                        'new_row_conditions' && (
                                        <div className="mt-4 rounded-xl bg-blue-50 p-4 text-xs text-blue-800 dark:bg-blue-950/30 dark:text-blue-200">
                                            Only newly added rows are eligible, and they must also match the conditions below.
                                        </div>
                                    )}

                                    {triggerType ===
                                        'manual' && (
                                        <div className="mt-4 rounded-xl bg-amber-50 p-4 text-xs text-amber-800 dark:bg-amber-950/30 dark:text-amber-200">
                                            Scheduler will not send automatically. Use Send Now on the saved automation to process matching unsent rows.
                                        </div>
                                    )}

                                    {triggerType ===
                                        'column_changed' && (
                                        <div className="mt-4 grid gap-4 md:grid-cols-2">
                                            <label>
                                                <span className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                                    Watch
                                                    Column
                                                </span>

                                                <select
                                                    className={`${inputClass} mt-1.5`}
                                                    value={
                                                        watchColumn
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        setWatchColumn(
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                >
                                                    <option value="">
                                                        Select
                                                        column
                                                        to
                                                        watch
                                                    </option>

                                                    {headers.map(
                                                        (
                                                            h
                                                        ) => (
                                                            <option
                                                                key={
                                                                    h
                                                                }
                                                                value={
                                                                    h
                                                                }
                                                            >
                                                                {
                                                                    h
                                                                }
                                                            </option>
                                                        )
                                                    )}
                                                </select>
                                            </label>

                                            <label>
                                                <span className="text-xs font-medium text-neutral-600 dark:text-neutral-300">
                                                    Only
                                                    when
                                                    new
                                                    value
                                                    equals
                                                    (optional)
                                                </span>

                                                <input
                                                    className={`${inputClass} mt-1.5`}
                                                    value={
                                                        watchValue
                                                    }
                                                    onChange={(
                                                        e
                                                    ) =>
                                                        setWatchValue(
                                                            e
                                                                .target
                                                                .value
                                                        )
                                                    }
                                                    placeholder="Approved"
                                                />
                                            </label>
                                        </div>
                                    )}

                                    {showConditions && (
                                        <div className="mt-5 rounded-xl border border-neutral-200 p-4 dark:border-neutral-800">
                                            <div className="flex flex-wrap items-center justify-between gap-3">
                                                <div>
                                                    <div className="text-sm font-medium text-neutral-900 dark:text-white">
                                                        Conditions
                                                    </div>
                                                    <div className="text-[11px] text-neutral-500">
                                                        Up
                                                        to
                                                        10
                                                        conditions.
                                                    </div>
                                                </div>

                                                <button
                                                    type="button"
                                                    onClick={
                                                        addCondition
                                                    }
                                                    className="inline-flex items-center gap-1.5 rounded-lg border border-neutral-200 px-3 py-2 text-xs dark:border-neutral-700"
                                                >
                                                    <Plus className="h-3.5 w-3.5" />
                                                    Add
                                                    Condition
                                                </button>
                                            </div>

                                            {conditions.length ===
                                            0 ? (
                                                <div className="mt-4 rounded-lg border border-dashed border-neutral-300 p-4 text-center text-xs text-neutral-500 dark:border-neutral-700">
                                                    No
                                                    conditions
                                                    added.
                                                </div>
                                            ) : (
                                                <div className="mt-4 space-y-3">
                                                    {conditions.map(
                                                        (
                                                            condition,
                                                            index
                                                        ) => (
                                                            <div
                                                                key={
                                                                    index
                                                                }
                                                                className="grid gap-2 rounded-xl bg-neutral-50 p-3 dark:bg-neutral-950/40 md:grid-cols-[1fr_190px_1fr_auto]"
                                                            >
                                                                <select
                                                                    className={
                                                                        inputClass
                                                                    }
                                                                    value={
                                                                        condition.column
                                                                    }
                                                                    onChange={(
                                                                        e
                                                                    ) =>
                                                                        updateCondition(
                                                                            index,
                                                                            'column',
                                                                            e
                                                                                .target
                                                                                .value
                                                                        )
                                                                    }
                                                                >
                                                                    <option value="">
                                                                        Select
                                                                        column
                                                                    </option>

                                                                    {headers.map(
                                                                        (
                                                                            h
                                                                        ) => (
                                                                            <option
                                                                                key={
                                                                                    h
                                                                                }
                                                                                value={
                                                                                    h
                                                                                }
                                                                            >
                                                                                {
                                                                                    h
                                                                                }
                                                                            </option>
                                                                        )
                                                                    )}
                                                                </select>

                                                                <select
                                                                    className={
                                                                        inputClass
                                                                    }
                                                                    value={
                                                                        condition.operator
                                                                    }
                                                                    onChange={(
                                                                        e
                                                                    ) =>
                                                                        updateCondition(
                                                                            index,
                                                                            'operator',
                                                                            e
                                                                                .target
                                                                                .value
                                                                        )
                                                                    }
                                                                >
                                                                    {Object.entries(
                                                                        operatorLabels
                                                                    ).map(
                                                                        ([
                                                                            value,
                                                                            label,
                                                                        ]) => (
                                                                            <option
                                                                                key={
                                                                                    value
                                                                                }
                                                                                value={
                                                                                    value
                                                                                }
                                                                            >
                                                                                {
                                                                                    label
                                                                                }
                                                                            </option>
                                                                        )
                                                                    )}
                                                                </select>

                                                                {conditionNeedsValue(
                                                                    condition.operator
                                                                ) ? (
                                                                    <input
                                                                        className={
                                                                            inputClass
                                                                        }
                                                                        value={
                                                                            condition.value
                                                                        }
                                                                        onChange={(
                                                                            e
                                                                        ) =>
                                                                            updateCondition(
                                                                                index,
                                                                                'value',
                                                                                e
                                                                                    .target
                                                                                    .value
                                                                            )
                                                                        }
                                                                        placeholder="Value"
                                                                    />
                                                                ) : (
                                                                    <div className="flex items-center rounded-xl border border-dashed border-neutral-200 px-3 text-xs text-neutral-400 dark:border-neutral-700">
                                                                        No
                                                                        value
                                                                        required
                                                                    </div>
                                                                )}

                                                                <button
                                                                    type="button"
                                                                    onClick={() =>
                                                                        removeCondition(
                                                                            index
                                                                        )
                                                                    }
                                                                    className="inline-flex h-10 w-10 items-center justify-center rounded-lg border border-red-200 text-red-600 dark:border-red-900/50"
                                                                    title="Remove condition"
                                                                >
                                                                    <X className="h-4 w-4" />
                                                                </button>
                                                            </div>
                                                        )
                                                    )}
                                                </div>
                                            )}
                                        </div>
                                    )}
                                </div>

                                <div className="mt-6 rounded-xl bg-emerald-50 p-4 text-xs text-emerald-800 dark:bg-emerald-950/30 dark:text-emerald-200">
                                    i-Touch Digital Service automatically maintains:{' '}
                                    <strong>
                                        i-Touch
                                        ID,
                                        WhatsApp
                                        Status,
                                        Message
                                        ID,
                                        Sent At,
                                        Error
                                    </strong>
                                    . Each automation deduplicates its own rows, so the same row is not sent twice by that automation.
                                </div>

                                <div className="mt-5 flex flex-wrap gap-3">
                                    <button
                                        type="button"
                                        onClick={() => saveAutomation(false)}
                                        className="inline-flex items-center gap-2 rounded-xl border border-neutral-200 bg-white px-5 py-3 text-sm font-medium text-neutral-800 hover:bg-neutral-50 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-100 dark:hover:bg-neutral-800"
                                    >
                                        <Save className="h-4 w-4" />
                                        Save Configuration
                                    </button>

                                    <button
                                        type="button"
                                        onClick={() => saveAutomation(true)}
                                        className="inline-flex items-center gap-2 rounded-xl bg-emerald-600 px-5 py-3 text-sm font-medium text-white hover:bg-emerald-700"
                                    >
                                        <Zap className="h-4 w-4" />
                                        Save &amp; Activate
                                    </button>
                                </div>

                                <p className="mt-2 text-[11px] text-neutral-500">
                                    Save Configuration keeps this Sheet/Tab, template, mappings, trigger and all conditions in your account. It will still be visible after page reload. You can save separate rules for multiple Sheets or even multiple rules for the same Sheet.
                                </p>
                            </div>
                        )}

                        <div
                            className={`${cardClass} p-5`}
                        >
                            <h2 className="font-semibold text-neutral-900 dark:text-white">
                                Active /
                                Saved
                                Automations
                            </h2>

                            <p className="mt-1 text-sm text-neutral-500">
                                Each saved automation keeps its own Sheet/Tab, template, mappings, trigger and conditions. You can save multiple Sheets and multiple rules. Automatic triggers are checked every minute; Send Now runs immediately.
                            </p>

                            {automations.length ===
                            0 ? (
                                <div className="mt-5 rounded-xl border border-dashed border-neutral-300 p-8 text-center text-sm text-neutral-500 dark:border-neutral-700">
                                    No Google
                                    Sheets
                                    WhatsApp
                                    automation
                                    yet.
                                </div>
                            ) : (
                                <div className="mt-5 space-y-3">
                                    {automations.map(
                                        (
                                            item
                                        ) => (
                                            <div
                                                key={
                                                    item.id
                                                }
                                                className="rounded-xl border border-neutral-200 p-4 dark:border-neutral-800"
                                            >
                                                <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                                                    <div className="min-w-0">
                                                        <div className="flex flex-wrap items-center gap-2">
                                                            <div className="font-medium text-neutral-900 dark:text-white">
                                                                {
                                                                    item.name
                                                                }
                                                            </div>

                                                            <span
                                                                className={`rounded-full px-2 py-1 text-[11px] font-medium ${
                                                                    item.active
                                                                        ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-300'
                                                                        : 'bg-neutral-100 text-neutral-600 dark:bg-neutral-800 dark:text-neutral-300'
                                                                }`}
                                                            >
                                                                {item.active
                                                                    ? 'Active'
                                                                    : 'Paused'}
                                                            </span>
                                                        </div>

                                                        <div className="mt-1 text-xs text-neutral-500">
                                                            {item.spreadsheet_title ||
                                                                item.spreadsheet_id}{' '}
                                                            ·{' '}
                                                            {
                                                                item.sheet_name
                                                            }{' '}
                                                            ·{' '}
                                                            {item
                                                                .channel_account
                                                                ?.display_name ||
                                                                'WhatsApp'}{' '}
                                                            ·{' '}
                                                            {item
                                                                .template
                                                                ?.name ||
                                                                'Template'}
                                                        </div>

                                                        <div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-[11px] text-neutral-500">
                                                            <span>
                                                                Trigger:{' '}
                                                                {triggerSummary(
                                                                    item
                                                                )}
                                                            </span>
                                                            <span>
                                                                Sent:{' '}
                                                                {
                                                                    item.sent_count
                                                                }
                                                            </span>
                                                            <span>
                                                                Failed:{' '}
                                                                {
                                                                    item.failed_count
                                                                }
                                                            </span>
                                                            <span>
                                                                Last
                                                                check:{' '}
                                                                {niceDate(
                                                                    item.last_checked_at
                                                                )}
                                                            </span>
                                                        </div>

                                                        {Array.isArray(
                                                            item.conditions
                                                        ) &&
                                                            item
                                                                .conditions
                                                                .length >
                                                                0 && (
                                                                <div className="mt-2 flex flex-wrap gap-1.5">
                                                                    {item.conditions
                                                                        .slice(
                                                                            0,
                                                                            3
                                                                        )
                                                                        .map(
                                                                            (
                                                                                condition,
                                                                                idx
                                                                            ) => (
                                                                                <span
                                                                                    key={
                                                                                        idx
                                                                                    }
                                                                                    className="rounded-md bg-neutral-100 px-2 py-1 text-[10px] text-neutral-600 dark:bg-neutral-800 dark:text-neutral-300"
                                                                                >
                                                                                    {conditionText(
                                                                                        condition
                                                                                    )}
                                                                                </span>
                                                                            )
                                                                        )}

                                                                    {item
                                                                        .conditions
                                                                        .length >
                                                                        3 && (
                                                                        <span className="rounded-md bg-neutral-100 px-2 py-1 text-[10px] text-neutral-600 dark:bg-neutral-800 dark:text-neutral-300">
                                                                            +
                                                                            {item
                                                                                .conditions
                                                                                .length -
                                                                                3}{' '}
                                                                            more
                                                                        </span>
                                                                    )}
                                                                </div>
                                                            )}

                                                        {item.last_error && (
                                                            <div className="mt-2 text-xs text-red-600 dark:text-red-400">
                                                                {
                                                                    item.last_error
                                                                }
                                                            </div>
                                                        )}
                                                    </div>

                                                    <div className="flex flex-wrap gap-2">
                                                        <button
                                                            type="button"
                                                            onClick={() =>
                                                                router.post(
                                                                    route(
                                                                        'client.google-sheets.automations.run',
                                                                        item.id
                                                                    ),
                                                                    {},
                                                                    {
                                                                        preserveScroll: true,
                                                                    }
                                                                )
                                                            }
                                                            className="inline-flex items-center gap-1.5 rounded-lg border border-emerald-200 px-3 py-2 text-xs text-emerald-700 disabled:opacity-40 dark:border-emerald-900/50 dark:text-emerald-300"
                                                        >
                                                            <Play className="h-3.5 w-3.5" />
                                                            Send
                                                            Now
                                                        </button>

                                                        <button
                                                            type="button"
                                                            onClick={() =>
                                                                router.patch(
                                                                    route(
                                                                        'client.google-sheets.automations.toggle',
                                                                        item.id
                                                                    ),
                                                                    {
                                                                        active: !item.active,
                                                                    },
                                                                    {
                                                                        preserveScroll: true,
                                                                    }
                                                                )
                                                            }
                                                            className="inline-flex items-center gap-1.5 rounded-lg border border-neutral-200 px-3 py-2 text-xs dark:border-neutral-700"
                                                        >
                                                            {item.active ? (
                                                                <CirclePause className="h-3.5 w-3.5" />
                                                            ) : (
                                                                <CirclePlay className="h-3.5 w-3.5" />
                                                            )}

                                                            {item.active
                                                                ? 'Pause'
                                                                : 'Activate'}
                                                        </button>

                                                        <button
                                                            type="button"
                                                            onClick={() => {
                                                                if (
                                                                    window.confirm(
                                                                        'Delete this Google Sheets automation?'
                                                                    )
                                                                ) {
                                                                    router.delete(
                                                                        route(
                                                                            'client.google-sheets.automations.destroy',
                                                                            item.id
                                                                        ),
                                                                        {
                                                                            preserveScroll: true,
                                                                        }
                                                                    );
                                                                }
                                                            }}
                                                            className="inline-flex items-center gap-1.5 rounded-lg border border-red-200 px-3 py-2 text-xs text-red-600 dark:border-red-900/50"
                                                        >
                                                            <Trash2 className="h-3.5 w-3.5" />
                                                            Delete
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        )
                                    )}
                                </div>
                            )}
                        </div>
                    </>
                )}
            </div>
        </ClientLayout>
    );
}

