'use client';

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

type Props = {
  initialValues: {
    provider: string;
    verifyToken: string;
    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 }: 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>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>Verify Token</label>
            <input name="webhookVerifyToken" type="text" defaultValue={initialValues.verifyToken} />
          </div>
          <div>
            <label>Signing Secret</label>
            <input
              name="sharedSecret"
              type="password"
              placeholder="Leave blank to keep current secret"
            />
          </div>
          <div>
            <label>Meta App Secret</label>
            <input
              name="appSecret"
              type="password"
              placeholder="Leave blank to keep current app secret"
            />
          </div>
          <div>
            <label>Meta Access Token</label>
            <input
              name="accessToken"
              type="password"
              placeholder="Leave blank to keep current access token"
            />
          </div>
          <div>
            <label>Meta Phone Number ID</label>
            <input
              name="phoneNumberId"
              type="text"
              defaultValue={initialValues.phoneNumberId}
              placeholder="e.g. 123456789012345"
            />
          </div>
          <label className="settings-checkbox">
            <span>
              <strong>Enable WhatsApp integration</strong>
              <small>Master switch for webhook verification and processing flow.</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>Event Subscriptions</label>
              <p>Select which normalized webhook events should be processed by the backend worker.</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 ? 'Saving...' : 'Save Changes'}
          </button>
        </div>
        {saveState.error ? <p className="form-error">{saveState.error}</p> : null}
        {saveState.success ? <p className="form-success">Settings updated.</p> : null}
      </form>

      <form action={testAction} className="surface-card">
        <div className="form-stack">
          <div>
            <label>Test 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>Test Sender Phone</label>
            <input name="senderPhone" type="text" placeholder="6281999000111" />
          </div>
          <p>
            Test payload will create a `message.inbound` event, so make sure that subscription is enabled
            if you want the worker to process it.
          </p>
        </div>
        <div className="button-row">
          <button type="submit" className="secondary-button" disabled={testPending}>
            {testPending ? 'Queueing...' : 'Send Test Payload'}
          </button>
        </div>
        {testState.error ? <p className="form-error">{testState.error}</p> : null}
        {testState.success ? <p className="form-success">Test webhook queued.</p> : null}
      </form>
    </div>
  );
}
