'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  MessageCircle, Copy, Check, RefreshCw, Trash2, Save, Loader2,
  CheckCircle2, AlertCircle, Eye, EyeOff, Power,
} from 'lucide-react';
import FeatureGuard from '@client/components/FeatureGuard';
import { useLanguage } from '@client/contexts/LanguageContext';
import PermissionDenied from '@client/components/ui/PermissionDenied';

interface BranchCredential {
  branch_id: string;
  branch_name: string;
  phone_number_id: string | null;
  waba_id: string | null;
  whatsapp_phone_number: string | null;
  display_name: string | null;
  is_active: boolean;
  configured: boolean;
  access_token_hint: string | null;
  app_secret_set: boolean;
  verify_token: string | null;
  webhook_url: string | null;
  created_at: string | null;
  updated_at: string | null;
  template_count: number;
  templates_synced_at: string | null;
}

interface DraftState {
  phone_number_id: string;
  waba_id: string;
  whatsapp_phone_number: string;
  display_name: string;
  access_token: string;
  app_secret: string;
  is_active: boolean;
}

const BLANK_DRAFT: DraftState = {
  phone_number_id: '',
  waba_id: '',
  whatsapp_phone_number: '',
  display_name: '',
  access_token: '',
  app_secret: '',
  is_active: true,
};

function CopyButton({ value, label }: { value: string | null | undefined; label: string }) {
  const [copied, setCopied] = useState(false);
  if (!value) return null;
  return (
    <button
      type="button"
      onClick={async () => {
        try {
          await navigator.clipboard.writeText(value);
          setCopied(true);
          setTimeout(() => setCopied(false), 1800);
        } catch { /* ignore */ }
      }}
      className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded-md transition-colors"
      style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground))' }}
      aria-label={`Copy ${label}`}
    >
      {copied ? <Check size={12} /> : <Copy size={12} />}
      {copied ? 'Copied' : 'Copy'}
    </button>
  );
}

export default function WhatsAppPage() {
  return (
    <FeatureGuard feature="whatsapp_agent" featureName="WhatsApp Agent">
      <WhatsAppPageInner />
    </FeatureGuard>
  );
}

function WhatsAppPageInner() {
  const { t } = useLanguage();
  const [branches, setBranches] = useState<BranchCredential[]>([]);
  const [selectedBranchId, setSelectedBranchId] = useState<string | null>(null);
  const [draft, setDraft] = useState<DraftState>(BLANK_DRAFT);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<{ ok: boolean; message: string } | null>(null);
  const [savedFlash, setSavedFlash] = useState<string | null>(null);
  const [showToken, setShowToken] = useState(false);
  const [showSecret, setShowSecret] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [forbidden, setForbidden] = useState(false);

  const selectedBranch = useMemo(
    () => branches.find((b) => b.branch_id === selectedBranchId) || null,
    [branches, selectedBranchId]
  );

  const loadBranches = useCallback(async () => {
    setLoading(true); setError(null);
    try {
      const res = await fetch('/api/channels/whatsapp/credentials');
      if (res.status === 403) { setForbidden(true); setLoading(false); return; }
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json() as { branches: BranchCredential[] };
      setBranches(data.branches || []);
      setSelectedBranchId((prev) => prev ?? data.branches?.[0]?.branch_id ?? null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load branches');
    } finally {
      setLoading(false);
    }
  }, []);

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

  useEffect(() => {
    if (!selectedBranch) { setDraft(BLANK_DRAFT); return; }
    setDraft({
      phone_number_id: selectedBranch.phone_number_id || '',
      waba_id: selectedBranch.waba_id || '',
      whatsapp_phone_number: selectedBranch.whatsapp_phone_number || '',
      display_name: selectedBranch.display_name || '',
      access_token: '',
      app_secret: '',
      is_active: selectedBranch.is_active,
    });
    setTestResult(null);
  }, [selectedBranch]);

  const onSave = async () => {
    if (!selectedBranchId) return;
    if (!draft.phone_number_id.trim()) { setError('Phone number ID is required'); return; }
    if (!selectedBranch?.configured && !draft.access_token.trim()) {
      setError('Access token is required on first save'); return;
    }
    setSaving(true); setError(null); setSavedFlash(null);
    try {
      const res = await fetch('/api/channels/whatsapp/credentials', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          branch_id: selectedBranchId,
          phone_number_id: draft.phone_number_id.trim(),
          waba_id: draft.waba_id.trim() || null,
          whatsapp_phone_number: draft.whatsapp_phone_number.trim() || null,
          display_name: draft.display_name.trim() || null,
          access_token: draft.access_token.trim() || undefined,
          app_secret: draft.app_secret.trim() || undefined,
          is_active: draft.is_active,
        }),
      });
      const data = await res.json() as { credential?: BranchCredential; error?: string };
      if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
      if (data.credential) {
        setBranches((prev) => prev.map((b) => (b.branch_id === selectedBranchId ? data.credential! : b)));
      }
      setSavedFlash('Credentials saved');
      setDraft((d) => ({ ...d, access_token: '', app_secret: '' }));
      setTimeout(() => setSavedFlash(null), 2500);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Save failed');
    } finally {
      setSaving(false);
    }
  };

  const onTest = async () => {
    if (!selectedBranchId) return;
    setTesting(true); setTestResult(null);
    try {
      const res = await fetch('/api/channels/whatsapp/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ branch_id: selectedBranchId }),
      });
      const data = await res.json() as { ok: boolean; display_phone_number?: string; verified_name?: string; waba_name?: string; error?: string };
      if (data.ok) {
        setTestResult({
          ok: true,
          message:
            `Connected` +
            (data.display_phone_number ? ' as ' + data.display_phone_number : '') +
            (data.verified_name ? ' (' + data.verified_name + ')' : '') +
            (data.waba_name ? ' — WABA: ' + data.waba_name : ''),
        });
      } else {
        setTestResult({ ok: false, message: data.error || 'Connection failed' });
      }
    } catch (err) {
      setTestResult({ ok: false, message: err instanceof Error ? err.message : 'Test failed' });
    } finally {
      setTesting(false);
    }
  };

  const onDisconnect = async () => {
    if (!selectedBranchId) return;
    if (!confirm('Disconnect WhatsApp for this branch? You will need to re-enter all credentials to reconnect.')) return;
    try {
      const res = await fetch(`/api/channels/whatsapp/credentials?branch_id=${encodeURIComponent(selectedBranchId)}`, { method: 'DELETE' });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      await loadBranches();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Disconnect failed');
    }
  };

  if (forbidden) {
    return <PermissionDenied sectionName="the WhatsApp section" />;
  }

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-6">
      <div className="flex items-start justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <MessageCircle size={22} style={{ color: 'hsl(142 76% 36%)' }} />
            <h1 className="text-2xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>
              {t('whatsapp.title', 'WhatsApp Business')}
            </h1>
          </div>
          <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {t('whatsapp.subtitle', 'Connect each branch to a Meta WhatsApp Business phone number. Customers will chat with your AI agent over WhatsApp.')}
          </p>
        </div>
        <button
          type="button" onClick={loadBranches}
          className="inline-flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium"
          style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground))' }}
        >
          <RefreshCw size={14} /> {t('common.refresh', 'Refresh')}
        </button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-16"><Loader2 className="animate-spin" /></div>
      ) : branches.length === 0 ? (
        <div className="rounded-xl border p-8 text-center" style={{ borderColor: 'hsl(var(--border))', backgroundColor: 'hsl(var(--card))' }}>
          <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {t('whatsapp.noBranches', 'You need at least one active branch before connecting WhatsApp.')}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-12 gap-6">
          {/* Branch picker */}
          <div className="col-span-12 md:col-span-3">
            <div className="rounded-xl border overflow-hidden" style={{ borderColor: 'hsl(var(--border))', backgroundColor: 'hsl(var(--card))' }}>
              <div className="px-4 py-3 text-xs font-bold uppercase tracking-wide" style={{ color: 'hsl(var(--muted-foreground))', borderBottom: '1px solid hsl(var(--border))' }}>
                {t('whatsapp.branches', 'Branches')}
              </div>
              <div className="max-h-[480px] overflow-y-auto">
                {branches.map((b) => {
                  const active = b.branch_id === selectedBranchId;
                  return (
                    <button
                      key={b.branch_id}
                      onClick={() => setSelectedBranchId(b.branch_id)}
                      className="w-full text-left px-4 py-3 flex items-center justify-between gap-2 transition-colors"
                      style={{
                        backgroundColor: active ? 'hsl(var(--muted))' : 'transparent',
                        borderLeft: active ? '3px solid hsl(142 76% 36%)' : '3px solid transparent',
                      }}
                    >
                      <div className="min-w-0">
                        <div className="font-medium text-sm truncate" style={{ color: 'hsl(var(--foreground))' }}>{b.branch_name}</div>
                        <div className="text-[11px] mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                          {b.configured ? (b.is_active ? 'Connected' : 'Disabled') : 'Not connected'}
                        </div>
                        {b.configured && b.waba_id && (
                          <div className="text-[11px] mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                            {b.templates_synced_at ? (
                              <>
                                {b.template_count} template{b.template_count !== 1 ? 's' : ''}
                                {' · synced '}
                                {new Date(b.templates_synced_at).toLocaleDateString()}
                              </>
                            ) : (
                              'No templates synced'
                            )}
                          </div>
                        )}
                      </div>
                      {b.configured && (
                        <span className="w-2 h-2 rounded-full flex-shrink-0" style={{ backgroundColor: b.is_active ? 'hsl(142 76% 36%)' : 'hsl(var(--muted-foreground))' }} />
                      )}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Editor + log */}
          <div className="col-span-12 md:col-span-9 space-y-6">
            {!selectedBranch ? (
              <div className="rounded-xl border p-6 text-sm" style={{ borderColor: 'hsl(var(--border))', backgroundColor: 'hsl(var(--card))', color: 'hsl(var(--muted-foreground))' }}>
                Select a branch to configure WhatsApp.
              </div>
            ) : (
              <>
                {/* Webhook block */}
                <section className="rounded-xl border p-5 space-y-4" style={{ borderColor: 'hsl(var(--border))', backgroundColor: 'hsl(var(--card))' }}>
                  <div>
                    <h2 className="text-sm font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('whatsapp.webhook.title', 'Step 1 — Configure Meta webhook')}</h2>
                    <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {t('whatsapp.webhook.help', 'Paste these into your WhatsApp Business app under Webhooks, then subscribe to the “messages” field.')}
                    </p>
                  </div>
                  <div className="grid grid-cols-1 gap-3">
                    <div>
                      <label className="text-xs font-medium mb-1 block" style={{ color: 'hsl(var(--muted-foreground))' }}>Callback URL</label>
                      <div className="flex gap-2">
                        <input readOnly value={selectedBranch.webhook_url || ''} className="flex-1 px-3 py-2 rounded-lg text-xs font-mono" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground))', border: '1px solid hsl(var(--border))' }} />
                        <CopyButton value={selectedBranch.webhook_url} label="webhook URL" />
                      </div>
                    </div>
                    <div>
                      <label className="text-xs font-medium mb-1 block" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        Verify token {!selectedBranch.verify_token && <span className="text-[10px]">(generated after first save)</span>}
                      </label>
                      <div className="flex gap-2">
                        <input readOnly value={selectedBranch.verify_token || ''} placeholder="Save credentials to generate" className="flex-1 px-3 py-2 rounded-lg text-xs font-mono" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground))', border: '1px solid hsl(var(--border))' }} />
                        <CopyButton value={selectedBranch.verify_token} label="verify token" />
                      </div>
                    </div>
                  </div>
                </section>

                {/* Credentials editor */}
                <section className="rounded-xl border p-5 space-y-4" style={{ borderColor: 'hsl(var(--border))', backgroundColor: 'hsl(var(--card))' }}>
                  <div>
                    <h2 className="text-sm font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('whatsapp.creds.title', 'Step 2 — Save your Meta credentials')}</h2>
                    <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {t('whatsapp.creds.help', 'Find these in your WhatsApp Business app: Phone Number ID and WABA ID under API Setup, Access Token under System Users, and App Secret under Basic Settings.')}
                    </p>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <Field label="Phone Number ID *" value={draft.phone_number_id}
                      onChange={(v) => setDraft((d) => ({ ...d, phone_number_id: v }))} placeholder="e.g. 123456789012345" />
                    <Field label="WABA ID" value={draft.waba_id}
                      onChange={(v) => setDraft((d) => ({ ...d, waba_id: v }))} placeholder="Optional" />
                    <Field label="WhatsApp Phone Number" value={draft.whatsapp_phone_number}
                      onChange={(v) => setDraft((d) => ({ ...d, whatsapp_phone_number: v }))} placeholder="E.164 e.g. +14155552671" />
                    <Field label="Display Name" value={draft.display_name}
                      onChange={(v) => setDraft((d) => ({ ...d, display_name: v }))} placeholder="e.g. Pizza Palace London" />
                    <div>
                      <label className="text-xs font-medium mb-1 block" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        Access Token {selectedBranch.access_token_hint && <span className="text-[10px]">(saved: {selectedBranch.access_token_hint})</span>}
                      </label>
                      <div className="relative">
                        <input
                          type={showToken ? 'text' : 'password'}
                          value={draft.access_token}
                          onChange={(e) => setDraft((d) => ({ ...d, access_token: e.target.value }))}
                          placeholder={selectedBranch.access_token_hint ? 'Leave blank to keep current' : 'EAA...'}
                          className="w-full px-3 py-2 pr-9 rounded-lg text-sm"
                          style={{ backgroundColor: 'hsl(var(--background))', color: 'hsl(var(--foreground))', border: '1px solid hsl(var(--border))' }}
                        />
                        <button type="button" onClick={() => setShowToken((s) => !s)} className="absolute right-2 top-1/2 -translate-y-1/2 p-1" aria-label="Toggle">
                          {showToken ? <EyeOff size={14} /> : <Eye size={14} />}
                        </button>
                      </div>
                    </div>
                    <div className="md:col-span-2">
                      <label className="text-xs font-medium mb-1 block" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        App Secret {selectedBranch.app_secret_set && <span className="text-[10px]">(saved)</span>}
                      </label>
                      <div className="relative">
                        <input
                          type={showSecret ? 'text' : 'password'}
                          value={draft.app_secret}
                          onChange={(e) => setDraft((d) => ({ ...d, app_secret: e.target.value }))}
                          placeholder={selectedBranch.app_secret_set ? 'Leave blank to keep current' : 'Required for signed webhook delivery'}
                          className="w-full px-3 py-2 pr-9 rounded-lg text-sm"
                          style={{ backgroundColor: 'hsl(var(--background))', color: 'hsl(var(--foreground))', border: '1px solid hsl(var(--border))' }}
                        />
                        <button type="button" onClick={() => setShowSecret((s) => !s)} className="absolute right-2 top-1/2 -translate-y-1/2 p-1" aria-label="Toggle">
                          {showSecret ? <EyeOff size={14} /> : <Eye size={14} />}
                        </button>
                      </div>
                      <p className="text-[11px] mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        Without an app secret we accept inbound webhooks unsigned (initial setup only). Add the secret as soon as your integration is verified.
                      </p>
                    </div>
                  </div>

                  <label className="flex items-center gap-2 text-sm" style={{ color: 'hsl(var(--foreground))' }}>
                    <input type="checkbox" checked={draft.is_active}
                      onChange={(e) => setDraft((d) => ({ ...d, is_active: e.target.checked }))} />
                    <Power size={14} /> Channel active (auto-reply to inbound messages)
                  </label>

                  {error && (
                    <div className="text-xs px-3 py-2 rounded-md flex items-center gap-2" style={{ backgroundColor: 'hsl(0 84% 60% / 0.1)', color: 'hsl(0 84% 50%)' }}>
                      <AlertCircle size={14} /> {error}
                    </div>
                  )}
                  {savedFlash && (
                    <div className="text-xs px-3 py-2 rounded-md flex items-center gap-2" style={{ backgroundColor: 'hsl(142 76% 36% / 0.1)', color: 'hsl(142 76% 30%)' }}>
                      <CheckCircle2 size={14} /> {savedFlash}
                    </div>
                  )}

                  <div className="flex flex-wrap gap-2 pt-2">
                    <button type="button" onClick={onSave} disabled={saving}
                      className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50"
                      style={{ backgroundColor: 'hsl(142 76% 36%)', color: 'white' }}>
                      {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />} Save credentials
                    </button>
                    <button type="button" onClick={onTest} disabled={testing || !selectedBranch.configured}
                      className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50"
                      style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground))' }}>
                      {testing ? <Loader2 size={14} className="animate-spin" /> : <CheckCircle2 size={14} />} Test connection
                    </button>
                    {selectedBranch.configured && (
                      <button type="button" onClick={onDisconnect}
                        className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium ml-auto"
                        style={{ backgroundColor: 'hsl(0 84% 60% / 0.1)', color: 'hsl(0 84% 50%)' }}>
                        <Trash2 size={14} /> Disconnect
                      </button>
                    )}
                  </div>

                  {testResult && (
                    <div className="text-xs px-3 py-2 rounded-md flex items-center gap-2"
                      style={{
                        backgroundColor: testResult.ok ? 'hsl(142 76% 36% / 0.1)' : 'hsl(0 84% 60% / 0.1)',
                        color: testResult.ok ? 'hsl(142 76% 30%)' : 'hsl(0 84% 50%)',
                      }}>
                      {testResult.ok ? <CheckCircle2 size={14} /> : <AlertCircle size={14} />} {testResult.message}
                    </div>
                  )}
                </section>

              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

function Field({ label, value, onChange, placeholder }: { label: string; value: string; onChange: (v: string) => void; placeholder?: string }) {
  return (
    <div>
      <label className="text-xs font-medium mb-1 block" style={{ color: 'hsl(var(--muted-foreground))' }}>{label}</label>
      <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder}
        className="w-full px-3 py-2 rounded-lg text-sm"
        style={{ backgroundColor: 'hsl(var(--background))', color: 'hsl(var(--foreground))', border: '1px solid hsl(var(--border))' }} />
    </div>
  );
}
