"use client";
import {
  Page,
  LegacyCard,
  BlockStack,
  InlineStack,
  Text,
  TextField,
  Select,
  Button,
  Icon,
  Spinner,
  Banner,
  Badge,
  Divider,
} from '@shopify/polaris';
import { PhoneIcon, NoteIcon, SaveIcon } from '@shopify/polaris-icons';
import React, { useCallback, useEffect, useState } from 'react';
import { useNavigate } from '@remix-run/react';
import {
  getCallTranscriptionSetupDetails,
  saveCallTranscriptionSetupDetails,
} from '../utils/voiceCallApi';
import { useApiFeedback } from '../utils/useApiFeedback';

const LANGUAGE_OPTIONS = [
  { label: 'English (US)', value: 'en_US' },
  { label: 'English (UK)', value: 'en_GB' },
  { label: 'English (India)', value: 'en_IN' },
  { label: 'Hindi', value: 'hi_IN' },
  { label: 'Spanish (Spain)', value: 'es_ES' },
  { label: 'Spanish (Mexico)', value: 'es_MX' },
  { label: 'French (France)', value: 'fr_FR' },
  { label: 'German', value: 'de_DE' },
  { label: 'Italian', value: 'it_IT' },
  { label: 'Portuguese (Brazil)', value: 'pt_BR' },
  { label: 'Arabic', value: 'ar_AR' },
  { label: 'Chinese (Simplified)', value: 'zh_CN' },
  { label: 'Japanese', value: 'ja_JP' },
  { label: 'Korean', value: 'ko_KR' },
  { label: 'Russian', value: 'ru_RU' },
];

function CallTranscriptionPage() {
  const navigate = useNavigate();
  const feedback = useApiFeedback();

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const [enabled, setEnabled] = useState(true);
  const [purpose, setPurpose] = useState('quality assurance and training');
  const [language, setLanguage] = useState('en_US');

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await getCallTranscriptionSetupDetails();
      const d = res?.data;
      if (d) {
        setEnabled(!!d.enabled);
        if (d.purpose) setPurpose(d.purpose);
        if (d.language) setLanguage(d.language);
      }
    } catch (e) {
      feedback.showError(e);
    } finally {
      setLoading(false);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => { load(); }, [load]);

  const handleSave = async () => {
    try {
      setSaving(true);
      const res = await saveCallTranscriptionSetupDetails({ enabled, purpose, language });
      feedback.showSuccess(res?.message || 'Call transcription setup saved.');
    } catch (e) {
      feedback.showError(e);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Page
      title="Call Transcription Setup"
      subtitle="Control whether WhatsApp voice calls placed through your business number are transcribed"
      backAction={{ content: 'Settings', onAction: () => navigate('/app/settings') }}
      primaryAction={{ content: 'Save', icon: SaveIcon, onAction: handleSave, loading: saving, disabled: loading }}
    >
      <BlockStack gap="400">
        {feedback.banner}

        {loading ? (
          <div style={{ padding: 48, textAlign: 'center' }}>
            <Spinner accessibilityLabel="Loading transcription setup" size="large" />
          </div>
        ) : (
          <>
            <LegacyCard sectioned>
              <InlineStack gap="300" blockAlign="center">
                <div style={{ width: 44, height: 44, borderRadius: 8, background: '#E0F2FE', color: '#0369A1', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon source={NoteIcon} />
                </div>
                <BlockStack gap="050">
                  <InlineStack gap="200" blockAlign="center">
                    <Text variant="headingMd" as="h2">Transcription status</Text>
                    <Badge tone={enabled ? 'success' : 'attention'}>
                      {enabled ? 'Enabled' : 'Disabled'}
                    </Badge>
                  </InlineStack>
                  <Text variant="bodySm" tone="subdued" as="p">
                    When enabled, WhatsApp business voice calls are transcribed for the purpose you set below.
                    Comply with local recording-disclosure laws before enabling.
                  </Text>
                </BlockStack>
              </InlineStack>

              <div style={{ marginTop: 16 }}>
                <InlineStack gap="200">
                  <Button
                    variant={enabled ? 'primary' : 'secondary'}
                    onClick={() => setEnabled(true)}
                  >
                    Enable
                  </Button>
                  <Button
                    variant={!enabled ? 'primary' : 'secondary'}
                    tone={!enabled ? 'critical' : undefined}
                    onClick={() => setEnabled(false)}
                  >
                    Disable
                  </Button>
                </InlineStack>
              </div>
            </LegacyCard>

            <LegacyCard sectioned title="Purpose disclosure">
              <BlockStack gap="200">
                <Text variant="bodySm" tone="subdued" as="p">
                  This text is used when the transcription purpose must be disclosed to the caller.
                  Keep it short and specific — e.g. <em>quality assurance and training</em>.
                </Text>
                <TextField
                  label="Purpose"
                  labelHidden
                  value={purpose}
                  onChange={setPurpose}
                  placeholder="e.g. quality assurance and training"
                  maxLength={250}
                  showCharacterCount
                  autoComplete="off"
                  disabled={!enabled}
                />
              </BlockStack>
            </LegacyCard>

            <LegacyCard sectioned title="Transcription language">
              <BlockStack gap="200">
                <Text variant="bodySm" tone="subdued" as="p">
                  Pick the primary language of your calls. Transcription accuracy is best when this
                  matches what your callers actually speak.
                </Text>
                <Select
                  label="Language"
                  labelHidden
                  options={LANGUAGE_OPTIONS}
                  value={language}
                  onChange={setLanguage}
                  disabled={!enabled}
                />
              </BlockStack>
            </LegacyCard>

            <Divider />

            <InlineStack align="space-between" blockAlign="center">
              <InlineStack gap="200" blockAlign="center">
                <Icon source={PhoneIcon} tone="subdued" />
                <Text variant="bodySm" tone="subdued" as="span">
                  Changes apply to all incoming and outgoing WhatsApp voice calls on your linked business number.
                </Text>
              </InlineStack>
              <Button variant="primary" onClick={handleSave} loading={saving} icon={SaveIcon}>
                Save changes
              </Button>
            </InlineStack>
          </>
        )}

        <Banner tone="info" title="Legal reminder">
          <p>
            Enabling call transcription may require caller consent under your local regulations
            (India — Telecom Act; EU — GDPR; California — CCPA; and similar). Confirm your
            deployment complies before switching this on.
          </p>
        </Banner>
      </BlockStack>
    </Page>
  );
}

export default CallTranscriptionPage;
