'use client';

import { useActionState } from 'react';
import {
  testWhatsappSettingsAction,
  updateWhatsappSettingsAction,
} from '../app/actions';

type Props = {
  labels: {
    provider: string;
    verifyToken: string;
    signingSecret: string;
    signingSecretPlaceholder: string;
    metaAppSecret: string;
    metaAppSecretPlaceholder: string;
    metaAccessToken: string;
    metaAccessTokenPlaceholder: string;
    metaPhoneNumberId: string;
    phonePlaceholder: string;
    enableIntegration: string;
    enableIntegrationCopy: string;
    eventSubscriptions: string;
    eventSubscriptionsCopy: string;
    saving: string;
    saveChanges: string;
    settingsUpdated: string;
    testProvider: string;
    testSenderPhone: string;
    testCopy: string;
    queueing: string;
    sendTestPayload: string;
    testQueued: string;
  };
  initialValues: {
    provider: string;
    verifyToken: string;
    sharedSecret: string;
    appSecret: string;
    accessToken: string;
    showSensitiveValues: boolean;
    phoneNumberId: string;
    isEnabled: boolean;
    subscriptions: string[];
    availableSubscriptions: Array<{
      key: string;
      label: string;
      description: string;
    }>;
  };
};

type FormState = {
  error?: string;
  success?: string;
};

const initialState: FormState = {};

export function WhatsappSettingsForm({ initialValues, labels }: Props) {
  const [saveState, saveAction, savePending] = useActionState(
    updateWhatsappSettingsAction,
    initialState,
  );
  const [testState, testAction, testPending] = useActionState(
    testWhatsappSettingsAction,
    initialState,
  );

  return (
    <div className="settings-form-stack">
      <form action={saveAction} className="surface-card">
        <div className="form-stack">
          <div>
            <label>{labels.provider}</label>
            <select name="provider" defaultValue={initialValues.provider}>
              <option value="meta">Meta</option>
              <option value="qontak">Qontak</option>
              <option value="default">Default</option>
            </select>
          </div>
          <div>
            <label>{labels.verifyToken}</label>
            <input name="webhookVerifyToken" type="text" defaultValue={initialValues.verifyToken} />
          </div>
          <div>
            <label>{labels.signingSecret}</label>
            <input
              name="sharedSecret"
              type={initialValues.showSensitiveValues ? 'text' : 'password'}
              defaultValue={initialValues.showSensitiveValues ? initialValues.sharedSecret : undefined}
              placeholder={labels.signingSecretPlaceholder}
            />
          </div>
          <div>
            <label>{labels.metaAppSecret}</label>
            <input
              name="appSecret"
              type={initialValues.showSensitiveValues ? 'text' : 'password'}
              defaultValue={initialValues.showSensitiveValues ? initialValues.appSecret : undefined}
              placeholder={labels.metaAppSecretPlaceholder}
            />
          </div>
          <div>
            <label>{labels.metaAccessToken}</label>
            <input
              name="accessToken"
              type={initialValues.showSensitiveValues ? 'text' : 'password'}
              defaultValue={initialValues.showSensitiveValues ? initialValues.accessToken : undefined}
              placeholder={labels.metaAccessTokenPlaceholder}
            />
          </div>
          <div>
            <label>{labels.metaPhoneNumberId}</label>
            <input
              name="phoneNumberId"
              type="text"
              defaultValue={initialValues.phoneNumberId}
              placeholder={labels.phonePlaceholder}
            />
          </div>
          <label className="settings-checkbox">
            <span>
              <strong>{labels.enableIntegration}</strong>
              <small>{labels.enableIntegrationCopy}</small>
            </span>
            <span className="settings-toggle">
              <input name="isEnabled" type="checkbox" defaultChecked={initialValues.isEnabled} />
              <span className="settings-toggle-ui" aria-hidden="true" />
            </span>
          </label>
          <div className="settings-subscriptions">
            <div>
              <label>{labels.eventSubscriptions}</label>
              <p>{labels.eventSubscriptionsCopy}</p>
            </div>
            {initialValues.availableSubscriptions.map((subscription) => (
              <label key={subscription.key} className="settings-subscription-row">
                <span>
                  <strong>{subscription.label}</strong>
                  <small>{subscription.description}</small>
                </span>
                <span className="settings-toggle">
                  <input
                    name="subscriptions"
                    type="checkbox"
                    value={subscription.key}
                    defaultChecked={initialValues.subscriptions.includes(subscription.key)}
                  />
                  <span className="settings-toggle-ui" aria-hidden="true" />
                </span>
              </label>
            ))}
          </div>
        </div>
        <div className="button-row">
          <button type="submit" className="primary-button" disabled={savePending}>
            {savePending ? labels.saving : labels.saveChanges}
          </button>
        </div>
        {saveState.error ? <p className="form-error">{saveState.error}</p> : null}
        {saveState.success ? <p className="form-success">{labels.settingsUpdated}</p> : null}
      </form>

      <form action={testAction} className="surface-card">
        <div className="form-stack">
          <div>
            <label>{labels.testProvider}</label>
            <select name="provider" defaultValue={initialValues.provider}>
              <option value="meta">Meta</option>
              <option value="qontak">Qontak</option>
              <option value="default">Default</option>
            </select>
          </div>
          <div>
            <label>{labels.testSenderPhone}</label>
            <input name="senderPhone" type="text" placeholder="6281999000111" />
          </div>
          <p>
            {labels.testCopy}
          </p>
        </div>
        <div className="button-row">
          <button type="submit" className="secondary-button" disabled={testPending}>
            {testPending ? labels.queueing : labels.sendTestPayload}
          </button>
        </div>
        {testState.error ? <p className="form-error">{testState.error}</p> : null}
        {testState.success ? <p className="form-success">{labels.testQueued}</p> : null}
      </form>
    </div>
  );
}
