import { useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { apiFetch } from '../lib/api';
import type { StatementData } from '../lib/types';

// ── Constants ─────────────────────────────────────────────────

const STEPS = ['Basic Information', 'Your Efforts', 'Conformance Status', 'Technical Specs', 'Feedback'];

const PREDEFINED_EFFORTS = [
  'Accessibility is part of our mission statement.',
  'Accessibility is part of our internal policies.',
  'Accessibility is integrated into our procurement practices.',
  'An accessibility officer or official has been appointed.',
  'Continual accessibility training is provided for employees.',
  'Clear accessibility targets and responsibilities exist within the organisation.',
  'Formal accessibility quality assurance methods exist within the organisation.',
];

const BROWSERS    = ['Chrome', 'Firefox', 'Safari', 'Edge', 'Internet Explorer'];
const OS_LIST     = ['Windows', 'macOS', 'iOS', 'Android', 'Linux'];
const AT_LIST     = ['JAWS', 'NVDA', 'VoiceOver', 'TalkBack', 'Dragon NaturallySpeaking'];
const TECH_LIST   = ['HTML', 'CSS', 'JavaScript', 'WAI-ARIA'];

const WCAG_STANDARDS = [
  { value: 'wcag22-aa',  label: 'WCAG 2.2 Level AA' },
  { value: 'wcag21-aaa', label: 'WCAG 2.1 Level AAA' },
  { value: 'wcag21-aa',  label: 'WCAG 2.1 Level AA' },
  { value: 'wcag21-a',   label: 'WCAG 2.1 Level A' },
  { value: 'wcag20-aaa', label: 'WCAG 2.0 Level AAA' },
  { value: 'wcag20-aa',  label: 'WCAG 2.0 Level AA' },
  { value: 'wcag20-a',   label: 'WCAG 2.0 Level A' },
  { value: 'section508', label: 'Section 508' },
  { value: 'other',      label: 'Other' },
];

const CONFORMANCE_LEVELS = [
  { value: 'fully-conformant',     label: 'Fully conformant',     desc: 'The content fully conforms to the accessibility standard without any exceptions.' },
  { value: 'partially-conformant', label: 'Partially conformant', desc: 'Some parts of the content do not fully conform to the accessibility standard.' },
  { value: 'non-conformant',       label: 'Non conformant',       desc: 'The content does not conform to the accessibility standard.' },
  { value: 'not-assessed',         label: 'Not assessed',         desc: 'The content has not been evaluated or the evaluation results are not available.' },
];

const EMPTY: StatementData = {
  status:     'none',
  page_id:    0,
  page_url:   '',
  edit_url:   '',
  updated_at: '',
  basic_info: { org_name: '', website: '', website_name: '' },
  efforts:    { selected: [], additional: [] },
  conformance:{ standard: 'wcag21-aa', custom_standard: '', level: 'partially-conformant', additional_notes: '' },
  tech_specs: { browsers: ['Chrome', 'Firefox', 'Safari', 'Edge'], operating_systems: ['Windows', 'macOS'], assistive_tech: [], technology_reliance: ['HTML', 'CSS', 'JavaScript'] },
  feedback:   { phone: '', email: '', address: '', response_duration: '2 business days' },
};

// ── Stepper ───────────────────────────────────────────────────

function Stepper({ step, total, labels }: { step: number; total: number; labels: string[] }) {
  return (
    <div className="aai-stepper" role="list">
      {Array.from({ length: total }, (_, i) => (
        <div key={i} className="aai-stepper__item" role="listitem">
          <div className={`aai-stepper__num${i < step ? ' aai-stepper__num--done' : i === step ? ' aai-stepper__num--active' : ''}`}>
            {i < step ? '✓' : i + 1}
          </div>
          {i === step && <span className="aai-stepper__label">{labels[i]}</span>}
          {i < total - 1 && <div className={`aai-stepper__line${i < step ? ' aai-stepper__line--done' : ''}`} />}
        </div>
      ))}
    </div>
  );
}

// ── Toggle ────────────────────────────────────────────────────

function Toggle({ checked, onChange }: { checked: boolean; onChange: (v: boolean) => void }) {
  return (
    <button
      role="switch"
      aria-checked={checked}
      className={`aai-toggle${checked ? ' aai-toggle--on' : ''}`}
      onClick={() => onChange(!checked)}
    />
  );
}

// ── CheckGroup ────────────────────────────────────────────────

function CheckGroup({
  options, selected, onChange,
}: { options: string[]; selected: string[]; onChange: (v: string[]) => void }) {
  const toggle = (v: string) =>
    onChange(selected.includes(v) ? selected.filter((x) => x !== v) : [...selected, v]);
  return (
    <div className="aai-check-group">
      {options.map((o) => (
        <label key={o} className="aai-check-item">
          <input type="checkbox" checked={selected.includes(o)} onChange={() => toggle(o)} />
          <span>{o}</span>
        </label>
      ))}
    </div>
  );
}

// ── Main component ────────────────────────────────────────────

export default function StatementGenerator() {
  const qc = useQueryClient();

  const { data: saved } = useQuery({
    queryKey: ['statement'],
    queryFn:  () => apiFetch<StatementData>('/statement'),
  });

  const [data, setData]       = useState<StatementData>(EMPTY);
  const [step, setStep]       = useState(0);
  const [addEffort, setAddEffort] = useState('');
  const [showAdd, setShowAdd] = useState(false);
  const [editing, setEditing] = useState(false);
  const [htmlStripped, setHtmlStripped] = useState(false);

  useEffect(() => {
    if (saved) {
      setData(saved);
      if (saved.status === 'none') setEditing(true);
    }
  }, [saved]);

  const save = useMutation({
    mutationFn: (publish: boolean) =>
      apiFetch<StatementData>('/statement', {
        method: 'POST',
        body:   JSON.stringify({ ...data, publish }),
      }),
    onSuccess: (result) => {
      // The server strips HTML tags from every text field for security. Detect
      // that here (rather than block it) so the user isn't left wondering why
      // their input silently disappeared.
      const submittedTextFields = [
        data.basic_info.org_name, data.basic_info.website_name,
        data.conformance.custom_standard, data.conformance.additional_notes,
        data.feedback.phone, data.feedback.address, data.feedback.response_duration,
      ];
      setHtmlStripped(submittedTextFields.some((v) => /[<>]/.test(v)));
      setData(result);
      setEditing(false);
      qc.invalidateQueries({ queryKey: ['statement'] });
    },
  });

  // ── helpers ──

  const setBasic       = (k: keyof StatementData['basic_info'],    v: string) => setData((d) => ({ ...d, basic_info:  { ...d.basic_info,  [k]: v } }));
  const setConformance = (k: keyof StatementData['conformance'],   v: string) => setData((d) => ({ ...d, conformance: { ...d.conformance, [k]: v } }));
  const setFeedback    = (k: keyof StatementData['feedback'],      v: string) => setData((d) => ({ ...d, feedback:    { ...d.feedback,    [k]: v } }));
  const setTechSpecs   = (k: keyof StatementData['tech_specs'],    v: string[]) => setData((d) => ({ ...d, tech_specs: { ...d.tech_specs,  [k]: v } }));
  const setEfforts     = (k: keyof StatementData['efforts'],       v: string[]) => setData((d) => ({ ...d, efforts:    { ...d.efforts,     [k]: v } }));

  const isValidEmail = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());

  const canNext = () => {
    if (step === 0) return data.basic_info.org_name.trim() && data.basic_info.website.trim() && data.basic_info.website_name.trim();
    return true;
  };

  // ── Success view ──

  if (!editing && data.status !== 'none') {
    return (
      <div className="aai-statement">
        <div className="aai-statement__header">
          <div>
            <h2 className="aai-pane-title">Accessibility Statement</h2>
            <p className="aai-muted">Generate and manage your website's accessibility statement.</p>
          </div>
        </div>

        {htmlStripped && (
          <p className="aai-stmt-warning" role="alert">
            ⚠ HTML tags aren't supported in statement fields and were removed from your input for security. Please review the fields below.
          </p>
        )}

        <div className="aai-stmt-card">
          <div className="aai-stmt-success">
            <span className="aai-stmt-success__icon" aria-hidden="true">✓</span>
            <div>
              <div className="aai-stmt-success__title">Statement generated</div>
              {data.updated_at && (
                <div className="aai-stmt-success__date">Last updated: {data.updated_at}</div>
              )}
            </div>
            <div className="aai-stmt-success__actions">
              {data.page_url && (
                <a href={data.page_url} target="_blank" rel="noopener noreferrer" className="aai-btn aai-btn--ghost aai-btn--sm">
                  👁 Preview
                </a>
              )}
              {data.edit_url && (
                <a href={data.edit_url} target="_blank" rel="noopener noreferrer" className="aai-btn aai-btn--ghost aai-btn--sm">
                  ✏ Edit in WP
                </a>
              )}
              <button className="aai-btn aai-btn--ghost aai-btn--sm" onClick={() => { setStep(0); setEditing(true); setHtmlStripped(false); }}>
                ✎ Edit form
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ── Wizard ──

  return (
    <div className="aai-statement">
      <div className="aai-statement__header">
        <div>
          <h2 className="aai-pane-title">Accessibility Statement</h2>
          <p className="aai-muted">Generate and manage your website's accessibility statement.</p>
        </div>
      </div>

      <div className="aai-stmt-card">
        <h3 className="aai-stmt-card__title">Generate statement</h3>

        <Stepper step={step} total={STEPS.length} labels={STEPS} />

        {/* ── Step 1: Basic Information ── */}
        {step === 0 && (
          <div className="aai-stmt-step">
            <h4>{STEPS[0]}</h4>
            <p className="aai-muted" style={{ marginBottom: 20 }}>
              To get started, tell us about your business and website. Fields marked with * must be filled in.
            </p>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Organisation name *</label>
              <p className="aai-stmt-field__hint">Example: Example Inc.</p>
              <input type="text" className="aai-stmt-input" value={data.basic_info.org_name}
                onChange={(e) => setBasic('org_name', e.target.value)} placeholder="Your organisation name" />
            </div>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Website *</label>
              <p className="aai-stmt-field__hint">Example: https://yourwebsite.com</p>
              <input type="url" className="aai-stmt-input" value={data.basic_info.website}
                onChange={(e) => setBasic('website', e.target.value)} placeholder="https://yourwebsite.com" />
            </div>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Website name *</label>
              <p className="aai-stmt-field__hint">Example: Example Site</p>
              <input type="text" className="aai-stmt-input" value={data.basic_info.website_name}
                onChange={(e) => setBasic('website_name', e.target.value)} placeholder="Your website name" />
            </div>
          </div>
        )}

        {/* ── Step 2: Your Efforts ── */}
        {step === 1 && (
          <div className="aai-stmt-step">
            <h4>{STEPS[1]}</h4>
            <p className="aai-muted" style={{ marginBottom: 20 }}>
              Select any current actions your organisation is taking to ensure web accessibility.
            </p>

            <CheckGroup
              options={PREDEFINED_EFFORTS}
              selected={data.efforts.selected}
              onChange={(v) => setEfforts('selected', v)}
            />

            {data.efforts.additional.map((eff, i) => (
              <div key={i} className="aai-stmt-add-row">
                <input type="text" className="aai-stmt-input" value={eff}
                  onChange={(e) => {
                    const next = [...data.efforts.additional];
                    next[i] = e.target.value;
                    setEfforts('additional', next);
                  }} />
                <button className="aai-btn aai-btn--ghost aai-btn--sm"
                  onClick={() => setEfforts('additional', data.efforts.additional.filter((_, j) => j !== i))}>
                  ✕
                </button>
              </div>
            ))}

            {showAdd ? (
              <div className="aai-stmt-add-row">
                <input type="text" className="aai-stmt-input" value={addEffort} autoFocus
                  onChange={(e) => setAddEffort(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && addEffort.trim()) {
                      setEfforts('additional', [...data.efforts.additional, addEffort.trim()]);
                      setAddEffort(''); setShowAdd(false);
                    }
                  }}
                  placeholder="Describe your effort…" />
                <button className="aai-btn aai-btn--primary aai-btn--sm"
                  onClick={() => { if (addEffort.trim()) { setEfforts('additional', [...data.efforts.additional, addEffort.trim()]); setAddEffort(''); } setShowAdd(false); }}>
                  Add
                </button>
              </div>
            ) : (
              <button className="aai-stmt-add-btn" onClick={() => setShowAdd(true)}>
                + Additional efforts
              </button>
            )}
          </div>
        )}

        {/* ── Step 3: Conformance Status ── */}
        {step === 2 && (
          <div className="aai-stmt-step">
            <h4>{STEPS[2]}</h4>

            <div className="aai-stmt-field" style={{ marginTop: 16 }}>
              <label className="aai-stmt-field__label">Which accessibility standard have you been following? *</label>
              <div className="aai-radio-group">
                {WCAG_STANDARDS.map((s) => (
                  <label key={s.value} className="aai-radio-item">
                    <input type="radio" name="standard" value={s.value}
                      checked={data.conformance.standard === s.value}
                      onChange={() => setConformance('standard', s.value)} />
                    <span>{s.label}</span>
                  </label>
                ))}
              </div>
              {data.conformance.standard === 'other' && (
                <input type="text" className="aai-stmt-input" style={{ marginTop: 8 }}
                  value={data.conformance.custom_standard}
                  onChange={(e) => setConformance('custom_standard', e.target.value)}
                  placeholder="Describe the standard" />
              )}
            </div>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Current content conformance status? *</label>
              <div className="aai-radio-group">
                {CONFORMANCE_LEVELS.map((l) => (
                  <label key={l.value} className="aai-radio-item aai-radio-item--desc">
                    <input type="radio" name="level" value={l.value}
                      checked={data.conformance.level === l.value}
                      onChange={() => setConformance('level', l.value)} />
                    <div>
                      <strong>{l.label}</strong>
                      <p>{l.desc}</p>
                    </div>
                  </label>
                ))}
              </div>
            </div>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Additional accessibility considerations</label>
              <p className="aai-stmt-field__hint">
                Example: While aiming for WCAG 2.1 Level AA conformance, we also implemented some Level AAA criteria.
              </p>
              <textarea className="aai-stmt-textarea" rows={4}
                value={data.conformance.additional_notes}
                onChange={(e) => setConformance('additional_notes', e.target.value)} />
            </div>

            <div className="aai-stmt-info-box">
              ℹ The statement will be generated based on the information you provide. Please ensure the details accurately reflect your website's accessibility status.
            </div>
          </div>
        )}

        {/* ── Step 4: Technical Specs ── */}
        {step === 3 && (
          <div className="aai-stmt-step">
            <h4>{STEPS[3]}</h4>
            <p className="aai-muted" style={{ marginBottom: 20 }}>
              Select the browsers, operating systems, and assistive technologies your site is compatible with.
            </p>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Compatible browsers</label>
              <CheckGroup options={BROWSERS} selected={data.tech_specs.browsers} onChange={(v) => setTechSpecs('browsers', v)} />
            </div>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Compatible operating systems</label>
              <CheckGroup options={OS_LIST} selected={data.tech_specs.operating_systems} onChange={(v) => setTechSpecs('operating_systems', v)} />
            </div>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Compatible assistive technologies</label>
              <CheckGroup options={AT_LIST} selected={data.tech_specs.assistive_tech} onChange={(v) => setTechSpecs('assistive_tech', v)} />
            </div>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Technology reliance</label>
              <CheckGroup options={TECH_LIST} selected={data.tech_specs.technology_reliance} onChange={(v) => setTechSpecs('technology_reliance', v)} />
            </div>
          </div>
        )}

        {/* ── Step 5: Feedback ── */}
        {step === 4 && (
          <div className="aai-stmt-step">
            <h4>{STEPS[4]}</h4>
            <p className="aai-muted" style={{ marginBottom: 20 }}>
              Provide contact details so users can report accessibility barriers.
            </p>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Phone</label>
              <input type="tel" className="aai-stmt-input" value={data.feedback.phone} inputMode="tel"
                onChange={(e) => setFeedback('phone', e.target.value.replace(/[^0-9+\-() .]/g, ''))}
                placeholder="+1 555 000 0000" />
            </div>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">E-mail *</label>
              <input type="email" className="aai-stmt-input" value={data.feedback.email} required
                onChange={(e) => setFeedback('email', e.target.value)} placeholder="accessibility@yoursite.com" />
              {!isValidEmail(data.feedback.email) && (
                <p className="aai-error" style={{ padding: '4px 0 0', fontSize: 12 }}>
                  A valid e-mail address is required so visitors can report accessibility barriers.
                </p>
              )}
            </div>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Address</label>
              <textarea className="aai-stmt-textarea" rows={3} value={data.feedback.address}
                onChange={(e) => setFeedback('address', e.target.value)} placeholder="123 Main St, City, Country" />
            </div>

            <div className="aai-stmt-field">
              <label className="aai-stmt-field__label">Typical response duration</label>
              <input type="text" className="aai-stmt-input" value={data.feedback.response_duration}
                onChange={(e) => setFeedback('response_duration', e.target.value)} placeholder="2 business days" />
            </div>
          </div>
        )}

        {/* ── Navigation ── */}
        <div className="aai-stmt-nav">
          {step > 0 ? (
            <button className="aai-btn aai-btn--ghost" onClick={() => setStep((s) => s - 1)}>
              ← Previous
            </button>
          ) : (
            <span />
          )}

          {step < STEPS.length - 1 ? (
            <button className="aai-btn aai-btn--primary" onClick={() => setStep((s) => s + 1)} disabled={!canNext()}>
              Next →
            </button>
          ) : (
            <button
              className="aai-btn aai-btn--primary"
              onClick={() => save.mutate(true)}
              disabled={save.isPending || !isValidEmail(data.feedback.email)}
            >
              {save.isPending ? 'Generating…' : 'Generate statement'}
            </button>
          )}
        </div>

        {save.isError && (
          <p className="aai-error" style={{ marginTop: 12 }}>{(save.error as Error).message}</p>
        )}
      </div>
    </div>
  );
}
