import axios from 'axios';
import Head from 'next/head';
import React from 'react';
import type { ReactElement } from 'react';
import SectionMain from '../components/SectionMain';
import { getPageTitle } from '../config';
import LayoutAuthenticated from '../layouts/Authenticated';

type Settings = {
  practice_name: string;
  logo_url: string;
  coach_name: string;
  coach_photo_url: string;
  coach_bio: string;
  coach_credentials: string;
  coach_niche: string;
  brand_color: string;
  default_booking_url: string;
  contact_email: string;
  custom_domain: string;
  social_links: unknown[];
  packages: unknown[];
  testimonials: unknown[];
  published: boolean;
  legal_entity_name: string;
  legal_contact_email: string;
  legal_terms_effective_date: string;
  legal_review_confirmed: boolean;
  reminders_enabled: boolean;
  default_reminder_minutes: number;
  timezone: string;
};

const emptySettings: Settings = {
  practice_name: '', logo_url: '', coach_name: '', coach_photo_url: '', coach_bio: '',
  coach_credentials: '', coach_niche: '', brand_color: 'teal', default_booking_url: '',
  contact_email: '', custom_domain: '', social_links: [], packages: [], testimonials: [], published: false,
  legal_entity_name: '', legal_contact_email: '', legal_terms_effective_date: '', legal_review_confirmed: false,
  reminders_enabled: true, default_reminder_minutes: 60, timezone: 'UTC',
};

const inputClass = 'w-full border border-[#19192d]/10 bg-white px-4 py-3 text-sm outline-none focus:border-[#147568]';

export default function WorkspaceSettings() {
  const [settings, setSettings] = React.useState<Settings>(emptySettings);
  const [jsonFields, setJsonFields] = React.useState({ social_links: '[]', packages: '[]', testimonials: '[]' });
  const [notice, setNotice] = React.useState('Loading workspace settings...');
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    axios.get('/coaching/workspace-settings').then((response) => {
      setSettings({ ...emptySettings, ...response.data });
      setJsonFields({
        social_links: JSON.stringify(response.data.social_links || [], null, 2),
        packages: JSON.stringify(response.data.packages || [], null, 2),
        testimonials: JSON.stringify(response.data.testimonials || [], null, 2),
      });
      setNotice('');
    }).catch((error) => {
      console.error('Could not load workspace settings', error);
      setNotice('Workspace settings could not be loaded. Retry by refreshing the page.');
    });
  }, []);

  function update(field: keyof Settings, value: string | boolean) {
    setSettings((current) => ({ ...current, [field]: value }));
  }

  async function save() {
    setSaving(true);
    setNotice('');
    try {
      const payload = {
        ...settings,
        social_links: JSON.parse(jsonFields.social_links),
        packages: JSON.parse(jsonFields.packages),
        testimonials: JSON.parse(jsonFields.testimonials),
      };
      const response = await axios.patch('/coaching/workspace-settings', payload);
      setSettings({ ...emptySettings, ...response.data });
      setNotice('Workspace settings saved. Invalid or placeholder booking links are never published.');
    } catch (error) {
      console.error('Could not save workspace settings', error);
      setNotice('Settings were not saved. Check required fields, JSON, email, and HTTPS booking URL.');
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      <Head><title>{getPageTitle('Workspace Settings')}</title></Head>
      <SectionMain>
        <div className='mx-auto max-w-5xl'>
          <div className='bg-[#19192d] p-7 text-white'>
            <p className='text-xs font-semibold uppercase tracking-[0.22em] text-[#147568]'>Public coaching practice</p>
            <h1 className='mt-3 text-2xl font-semibold'>Workspace settings</h1>
            <p className='mt-2 text-sm text-[#fffdf9]'>Configure identity and booking without editing template code. Preview before enabling publication.</p>
          </div>
          {notice && <div role='status' className='border border-[#147568]/20 bg-white px-4 py-3 text-sm font-semibold text-[#19192d]'>{notice}</div>}
          <div className='mt-6 grid gap-5 border border-[#19192d]/10 bg-white p-7 md:grid-cols-2'>
            {([
              ['practice_name', 'Practice name'], ['coach_name', 'Coach name'], ['coach_niche', 'Coaching niche'],
              ['coach_credentials', 'Credentials'], ['contact_email', 'Contact email'], ['default_booking_url', 'Default HTTPS booking URL'],
              ['logo_url', 'Logo URL'], ['coach_photo_url', 'Coach photo URL'], ['custom_domain', 'Production domain'],
              ['legal_entity_name', 'Legal entity name'], ['legal_contact_email', 'Legal contact email'], ['legal_terms_effective_date', 'Terms effective date (YYYY-MM-DD)'],
            ] as Array<[keyof Settings, string]>).map(([field, label]) => (
              <label key={field} className='block text-sm font-semibold'>{label}
                <input className={`${inputClass} mt-2`} value={String(settings[field] || '')} onChange={(event) => update(field, event.target.value)} />
              </label>
            ))}
            <label className='block text-sm font-semibold md:col-span-2'>Coach bio
              <textarea className={`${inputClass} mt-2 min-h-32`} value={settings.coach_bio} onChange={(event) => update('coach_bio', event.target.value)} />
            </label>
            <label className='block text-sm font-semibold'>Brand color
              <select className={`${inputClass} mt-2`} value={settings.brand_color} onChange={(event) => update('brand_color', event.target.value)}>
                {['teal', 'navy', 'indigo', 'forest', 'clay'].map((color) => <option key={color}>{color}</option>)}
              </select>
            </label>
            <label className='flex items-center gap-3 text-sm font-semibold'>
              <input type='checkbox' checked={settings.legal_review_confirmed} onChange={(event) => update('legal_review_confirmed', event.target.checked)} />
              I confirm the Terms and Privacy text was reviewed for this entity and launch market
            </label>
            <label className='flex items-center gap-3 text-sm font-semibold'>
              <input type='checkbox' checked={settings.published} onChange={(event) => update('published', event.target.checked)} />
              Publish configured public identity
            </label>
            <label className='flex items-center gap-3 text-sm font-semibold'>
              <input type='checkbox' checked={settings.reminders_enabled} onChange={(event) => update('reminders_enabled', event.target.checked)} />
              Enable in-app reminders
            </label>
            <label className='block text-sm font-semibold'>Default reminder
              <select className={`${inputClass} mt-2`} value={settings.default_reminder_minutes} onChange={(event) => setSettings((current) => ({ ...current, default_reminder_minutes: Number(event.target.value) }))}>
                <option value='10'>10 minutes before</option><option value='60'>1 hour before</option><option value='1440'>1 day before</option>
              </select>
            </label>
            <label className='block text-sm font-semibold'>Workspace timezone
              <input className={`${inputClass} mt-2`} value={settings.timezone} onChange={(event) => update('timezone', event.target.value)} placeholder='America/Chicago' />
            </label>
            {(['social_links', 'packages', 'testimonials'] as const).map((field) => (
              <label key={field} className='block text-sm font-semibold md:col-span-2'>{field.replace('_', ' ')} JSON
                <textarea className={`${inputClass} mt-2 min-h-36 font-mono`} value={jsonFields[field]} onChange={(event) => setJsonFields((current) => ({ ...current, [field]: event.target.value }))} />
              </label>
            ))}
            <button type='button' disabled={saving} onClick={save} className='bg-[#147568] px-5 py-3 font-semibold text-white disabled:opacity-50'>
              {saving ? 'Saving...' : 'Save settings'}
            </button>
          </div>
        </div>
      </SectionMain>
    </>
  );
}

WorkspaceSettings.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};
