// ═══════════════════════════════════════════════════════════════════
// KINGDOMID CLIENT — Settings Page
// Business info, AI assistant behavior, faith settings, financial,
// and booking configuration — client's own self-service settings.
// ═══════════════════════════════════════════════════════════════════

import { useEffect, useState } from 'react';
import { useClient } from '../hooks/useClient';
import { apiGet, apiPost } from '../lib/firebase';
import { Save, Loader2, Building2, Bot, Church, DollarSign, CalendarCheck } from 'lucide-react';

interface ClientSettings {
  business_name: string;
  owner_name: string;
  owner_email: string;
  owner_phone: string;
  services: (string | { name: string; [key: string]: any })[];
  business_hours: Record<string, any>;
  ai_name: string;
  voice_gender: 'male' | 'female';
  faith_closing_phrase: string;
  escalation_number: string;
  google_review_url: string;
  faith_affiliation: string;
  scripture_in_sms: boolean;
  scripture_in_email: boolean;
  avg_ticket_value: number;
  booking_system: string;
  intake_form_url: string;
}

const NAVY = '#0D1B3E';
const GOLD = '#C9A227';
const TAN = '#F6F0E4';
const TAN_DARK = '#E3D3B1';
const MUTED = '#8A7F68';

function SectionCard({ icon: Icon, title, subtitle, children }: { icon: any; title: string; subtitle?: string; children: React.ReactNode }) {
  return (
    <div style={{ background: 'white', borderRadius: 14, padding: 26, marginBottom: 18, border: `1px solid ${TAN_DARK}`, boxShadow: '0 1px 3px rgba(13,27,62,0.06)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
        <div style={{ width: 32, height: 32, borderRadius: 9, background: `${NAVY}12`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon size={16} color={NAVY} />
        </div>
        <div style={{ fontSize: 15, fontWeight: 800, color: NAVY, fontFamily: 'Georgia, serif' }}>{title}</div>
      </div>
      {subtitle && <div style={{ fontSize: 12, color: MUTED, marginBottom: 18, marginLeft: 42 }}>{subtitle}</div>}
      <div style={{ marginTop: 18 }}>{children}</div>
    </div>
  );
}

function Field({ label, children, hint }: { label: string; children: React.ReactNode; hint?: string }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <label style={{ display: 'block', fontSize: 12, fontWeight: 700, color: MUTED, marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</label>
      {children}
      {hint && <div style={{ fontSize: 11.5, color: MUTED, marginTop: 5 }}>{hint}</div>}
    </div>
  );
}

const inputStyle: React.CSSProperties = {
  width: '100%', padding: '10px 13px', borderRadius: 8, border: `1px solid ${TAN_DARK}`,
  fontSize: 14, color: NAVY, background: TAN,
};

export default function SettingsPage() {
  const { client } = useClient();
  const [settings, setSettings] = useState<ClientSettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [saveMsg, setSaveMsg] = useState('');
  const [servicesText, setServicesText] = useState('');
  const [originalServices, setOriginalServices] = useState<any[]>([]); // preserves extra fields (duration, price, etc.) on services that already had them

  useEffect(() => {
    if (client?.id) loadSettings();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [client?.id]);

  const loadSettings = async () => {
    setLoading(true);
    setError('');
    try {
      const res = await apiGet<{ settings: ClientSettings }>(`/api/client-settings/${client!.id}`);
      setSettings(res.settings);
      const rawServices = res.settings.services || [];
      setOriginalServices(rawServices);
      const displayNames = rawServices.map((s: any) =>
        typeof s === 'string' ? s : (s?.name || '')
      ).filter(Boolean);
      setServicesText(displayNames.join(', '));
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const update = (field: keyof ClientSettings, value: any) => {
    setSettings((prev) => (prev ? { ...prev, [field]: value } : prev));
  };

  const handleSave = async () => {
    if (!settings || !client?.id) return;
    setSaving(true);
    setSaveMsg('');
    try {
      // Merge edited names back onto the original service objects by
      // position, so fields like duration/price aren't silently wiped.
      // New entries beyond the original count become plain {name} objects.
      const editedNames = servicesText.split(',').map(s => s.trim()).filter(Boolean);
      const servicesArray = editedNames.map((name, i) => {
        const original = originalServices[i];
        if (original && typeof original === 'object') {
          return { ...original, name };
        }
        return { name };
      });
      const res = await apiPost<{ success: boolean; vapi_updated: boolean; vapi_error: string | null }>(
        `/api/client-settings/${client.id}`,
        { ...settings, services: servicesArray }
      );
      setSaveMsg(
        res.vapi_error
          ? `Saved, but your AI assistant update failed: ${res.vapi_error}`
          : res.vapi_updated
            ? 'Saved — your AI assistant has been updated with the new settings.'
            : 'Saved.'
      );
    } catch (err: any) {
      setSaveMsg(`Failed: ${err.message}`);
    } finally {
      setSaving(false);
    }
  };

  if (loading || !settings) {
    return (
      <div style={{ padding: 60, textAlign: 'center' }}>
        <Loader2 size={26} color={GOLD} style={{ margin: '0 auto 12px' }} />
        <p style={{ color: MUTED }}>Loading settings...</p>
      </div>
    );
  }

  if (error) return <div style={{ padding: 40, color: '#B91C1C' }}>{error}</div>;

  return (
    <div style={{ padding: '28px 32px', maxWidth: 760, margin: '0 auto' }}>

      <div style={{ marginBottom: 24 }}>
        <h1 style={{ fontSize: 24, fontWeight: 800, color: NAVY, fontFamily: 'Georgia, serif', marginBottom: 4 }}>Settings</h1>
        <p style={{ fontSize: 13, color: MUTED }}>Manage your business info and how your AI assistant represents you</p>
      </div>

      <SectionCard icon={Building2} title="Business Info">
        <Field label="Business Name">
          <input style={inputStyle} value={settings.business_name} onChange={e => update('business_name', e.target.value)} />
        </Field>
        <div style={{ display: 'flex', gap: 14 }}>
          <div style={{ flex: 1 }}>
            <Field label="Owner Name">
              <input style={inputStyle} value={settings.owner_name} onChange={e => update('owner_name', e.target.value)} />
            </Field>
          </div>
          <div style={{ flex: 1 }}>
            <Field label="Owner Phone">
              <input style={inputStyle} value={settings.owner_phone} onChange={e => update('owner_phone', e.target.value)} placeholder="+1..." />
            </Field>
          </div>
        </div>
        <Field label="Owner Email">
          <input style={inputStyle} type="email" value={settings.owner_email} onChange={e => update('owner_email', e.target.value)} />
        </Field>
        <Field label="Services Offered" hint="Comma-separated — e.g. Individual Counseling, Couples Therapy, Group Sessions">
          <input style={inputStyle} value={servicesText} onChange={e => setServicesText(e.target.value)} />
        </Field>
      </SectionCard>

      <SectionCard icon={Bot} title="AI Assistant" subtitle="Changes here update what your AI actually says on live calls">
        <div style={{ display: 'flex', gap: 14 }}>
          <div style={{ flex: 1 }}>
            <Field label="AI Assistant Name">
              <input style={inputStyle} value={settings.ai_name} onChange={e => update('ai_name', e.target.value)} />
            </Field>
          </div>
          <div style={{ flex: 1 }}>
            <Field label="Voice">
              <select style={inputStyle} value={settings.voice_gender} onChange={e => update('voice_gender', e.target.value)}>
                <option value="female">Female</option>
                <option value="male">Male</option>
              </select>
            </Field>
          </div>
        </div>
        <Field label="Closing Phrase" hint="What your AI says at the end of every call">
          <input style={inputStyle} value={settings.faith_closing_phrase} onChange={e => update('faith_closing_phrase', e.target.value)} />
        </Field>
        <Field label="Escalation Number" hint="Urgent calls get transferred here">
          <input style={inputStyle} value={settings.escalation_number} onChange={e => update('escalation_number', e.target.value)} placeholder="+1..." />
        </Field>
        <Field label="Google Review Link">
          <input style={inputStyle} value={settings.google_review_url} onChange={e => update('google_review_url', e.target.value)} placeholder="https://..." />
        </Field>
      </SectionCard>

      <SectionCard icon={Church} title="Faith Settings">
        <Field label="Faith Affiliation">
          <input style={inputStyle} value={settings.faith_affiliation} onChange={e => update('faith_affiliation', e.target.value)} placeholder="e.g. Non-denominational Christian" />
        </Field>
        <div style={{ display: 'flex', gap: 24, marginTop: 4 }}>
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: NAVY, cursor: 'pointer' }}>
            <input type="checkbox" checked={settings.scripture_in_sms} onChange={e => update('scripture_in_sms', e.target.checked)} />
            Include scripture in SMS
          </label>
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: NAVY, cursor: 'pointer' }}>
            <input type="checkbox" checked={settings.scripture_in_email} onChange={e => update('scripture_in_email', e.target.checked)} />
            Include scripture in email
          </label>
        </div>
      </SectionCard>

      <SectionCard icon={DollarSign} title="Financial" subtitle="Drives the revenue math on your KingdomInsights reports">
        <Field label="Average Ticket Value" hint="Your typical revenue per client/appointment">
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ color: MUTED, fontSize: 14 }}>$</span>
            <input
              style={{ ...inputStyle, width: 140 }}
              type="number" min={0} step={0.01}
              value={settings.avg_ticket_value}
              onChange={e => update('avg_ticket_value', parseFloat(e.target.value) || 0)}
            />
          </div>
        </Field>
      </SectionCard>

      <SectionCard icon={CalendarCheck} title="Booking">
        <Field label="Booking System">
          <select style={inputStyle} value={settings.booking_system} onChange={e => update('booking_system', e.target.value)}>
            <option value="manual">Manual</option>
            <option value="google_calendar">Google Calendar</option>
            <option value="calendly">Calendly</option>
            <option value="ghl">GoHighLevel</option>
          </select>
        </Field>
        <Field label="Intake Form URL">
          <input style={inputStyle} value={settings.intake_form_url} onChange={e => update('intake_form_url', e.target.value)} placeholder="https://..." />
        </Field>
      </SectionCard>

      <button
        onClick={handleSave}
        disabled={saving}
        style={{
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          width: '100%', padding: '13px 20px', borderRadius: 10, border: 'none',
          background: NAVY, color: 'white', fontWeight: 700, fontSize: 14,
          cursor: saving ? 'not-allowed' : 'pointer', marginBottom: 10,
        }}
      >
        {saving ? <Loader2 size={16} /> : <Save size={16} />}
        {saving ? 'Saving...' : 'Save Settings'}
      </button>

      {saveMsg && <div style={{ fontSize: 13, color: MUTED, textAlign: 'center' }}>{saveMsg}</div>}
    </div>
  );
}
