import { useState, useEffect, useCallback } from 'react';
import { colors, fonts } from '@formiq/core';
import {
  type FormSchema as CoreFormSchema, type FormQuestion,
  parseFormSchema, renderHintForType, extractBrandedMeta,
  privacyFooterText,
} from '@formiq/core/forms';
import { api } from '../api';

const INDUSTRIES = [
  { value: 'psychology', label: 'Psychology' },
  { value: 'allied_health', label: 'Allied Health (General)' },
  { value: 'physiotherapy', label: 'Physiotherapy' },
  { value: 'occupational_therapy', label: 'Occupational Therapy' },
  { value: 'speech_pathology', label: 'Speech Pathology' },
  { value: 'dietetics', label: 'Dietetics & Nutrition' },
  { value: 'social_work', label: 'Social Work' },
  { value: 'other', label: 'Other Allied Health' },
];

type GeneratedForm = {
  id: string;
  formTitle: string;
  industry: string;
  generationStatus: 'generating' | 'complete' | 'failed';
  ahpraCompliant?: boolean;
  complianceNotes?: string;
  formSchemaJson?: string;
  createdAt: string;
};

// FormSchema is the canonical shape from @formiq/core/forms — same
// source-of-truth used by the Wix Astro renderer and the standalone
// Next.js app. parseFormSchema normalises legacy fixtures (sections.fields
// vs sections.questions) into this shape.
type FormSchema = CoreFormSchema;

const POLL_INTERVAL_MS = 3000;
const MAX_POLLS = 60; // 3 min timeout

export default function FormsTab() {
  const [view, setView] = useState<'list' | 'generate' | 'preview'>('list');
  const [forms, setForms] = useState<GeneratedForm[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedForm, setSelectedForm] = useState<GeneratedForm | null>(null);

  const loadForms = useCallback(async () => {
    setLoading(true);
    try {
      const data = await api<{ forms: GeneratedForm[] }>('/forms');
      setForms(data.forms ?? []);
    } catch {
      setForms([]);
    } finally {
      setLoading(false);
    }
  }, []);

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

  if (view === 'generate') {
    return (
      <GenerateView
        onCancel={() => setView('list')}
        onComplete={(form) => {
          setForms(prev => [form, ...prev.filter(f => f.id !== form.id)]);
          setSelectedForm(form);
          setView('preview');
        }}
      />
    );
  }

  if (view === 'preview' && selectedForm) {
    return (
      <PreviewView
        form={selectedForm}
        onBack={() => { setSelectedForm(null); setView('list'); }}
        onRegenerate={() => setView('generate')}
      />
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-lg font-bold" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>Generated Forms</h2>
        <button
          onClick={() => setView('generate')}
          className="px-4 py-2 rounded-lg text-sm font-medium"
          style={{ backgroundColor: colors.primary, color: '#fff' }}
        >
          + New Form
        </button>
      </div>

      {loading ? (
        <p className="text-sm" style={{ color: colors.textSecondary }}>Loading forms…</p>
      ) : forms.length === 0 ? (
        <EmptyState onGenerate={() => setView('generate')} />
      ) : (
        <div className="grid gap-3">
          {forms.map(form => (
            <FormCard
              key={form.id}
              form={form}
              onClick={() => { setSelectedForm(form); setView('preview'); }}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function EmptyState({ onGenerate }: { onGenerate: () => void }) {
  return (
    <div
      className="p-8 rounded-lg text-center"
      style={{ border: `2px dashed ${colors.border}`, backgroundColor: '#fafafa' }}
    >
      <p className="text-2xl mb-2">📋</p>
      <p className="font-medium mb-1" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>Your first form takes 60 seconds</p>
      <p className="text-sm mb-4" style={{ color: colors.textSecondary }}>
        Select your specialty and FormIQ builds a complete, AHPRA-compliant patient intake form — tailored to your practice.
      </p>
      <button
        onClick={onGenerate}
        className="px-4 py-2 rounded-lg text-sm font-medium"
        style={{ backgroundColor: colors.primary, color: '#fff' }}
      >
        Generate My First Form
      </button>
    </div>
  );
}

function FormCard({ form, onClick }: { form: GeneratedForm; onClick: () => void }) {
  const statusColor = form.generationStatus === 'complete'
    ? '#16a34a' : form.generationStatus === 'failed' ? '#dc2626' : colors.primary;
  const statusLabel = form.generationStatus === 'complete'
    ? 'Complete' : form.generationStatus === 'failed' ? 'Failed' : 'Generating…';

  return (
    <div
      className="p-4 rounded-lg bg-white cursor-pointer"
      style={{ border: `1px solid ${colors.border}` }}
      onClick={onClick}
    >
      <div className="flex items-center justify-between">
        <div>
          <p className="font-medium" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>{form.formTitle || 'Untitled Form'}</p>
          <p className="text-sm mt-0.5" style={{ color: colors.textSecondary }}>
            {INDUSTRIES.find(i => i.value === form.industry)?.label ?? form.industry}
            {' · '}
            {new Date(form.createdAt).toLocaleDateString()}
          </p>
        </div>
        <div className="flex items-center gap-2">
          {form.generationStatus === 'complete' && form.ahpraCompliant === true && (
            <span className="text-xs px-2 py-0.5 rounded-full" style={{ backgroundColor: '#dcfce7', color: '#16a34a' }}>
              AHPRA ✓
            </span>
          )}
          {form.generationStatus === 'complete' && form.ahpraCompliant === false && (
            <span className="text-xs px-2 py-0.5 rounded-full" style={{ backgroundColor: '#fef2f2', color: '#dc2626' }}>
              Review
            </span>
          )}
          <span className="text-xs font-medium" style={{ color: statusColor }}>{statusLabel}</span>
          <span style={{ color: colors.border }}>›</span>
        </div>
      </div>
    </div>
  );
}

function GenerateView({
  onCancel,
  onComplete,
}: {
  onCancel: () => void;
  onComplete: (form: GeneratedForm) => void;
}) {
  const [industry, setIndustry] = useState('');
  const [instructions, setInstructions] = useState('');
  const [status, setStatus] = useState<'idle' | 'generating' | 'error'>('idle');
  const [progress, setProgress] = useState(0);
  const [progressMsg, setProgressMsg] = useState('');
  const [error, setError] = useState('');

  async function handleGenerate() {
    if (!industry) { setError('Please select an industry.'); return; }
    setError('');
    setStatus('generating');
    setProgress(10);
    setProgressMsg('Starting form generation…');

    try {
      const { jobId, formId } = await api<{ jobId: string; formId: string }>('/forms/generate', {
        method: 'POST',
        body: { industry, customInstructions: instructions },
      });

      setProgress(20);
      setProgressMsg('AI is building your form…');

      // Poll job status
      let polls = 0;
      while (polls < MAX_POLLS) {
        await sleep(POLL_INTERVAL_MS);
        polls++;

        const job = await api<{
          status: string;
          progress?: number;
          message?: string;
          result?: { type: string; schema?: FormSchema; title?: string; ahpraCompliant?: boolean; complianceNotes?: string };
        }>(`/jobs/${jobId}`);

        if (job.progress) setProgress(Math.max(20, job.progress));
        if (job.message) setProgressMsg(job.message);

        if (job.status === 'complete' && job.result?.type === 'form_generated') {
          const form: GeneratedForm = {
            id: formId,
            formTitle: job.result.title ?? 'Generated Form',
            industry,
            generationStatus: 'complete',
            ahpraCompliant: job.result.ahpraCompliant,
            complianceNotes: job.result.complianceNotes,
            formSchemaJson: job.result.schema ? JSON.stringify(job.result.schema) : undefined,
            createdAt: new Date().toISOString(),
          };
          onComplete(form);
          return;
        }
        if (job.status === 'failed') {
          throw new Error(job.message ?? 'Form generation failed.');
        }
      }
      throw new Error('Generation timed out. Please try again.');
    } catch (err: unknown) {
      setStatus('error');
      setError(err instanceof Error ? err.message : 'Generation failed.');
    }
  }

  return (
    <div className="max-w-lg">
      <button
        onClick={onCancel}
        className="text-sm mb-4 flex items-center gap-1"
        style={{ color: colors.textSecondary }}
      >
        ← Back to Forms
      </button>

      <h2 className="text-lg font-bold mb-4" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>Generate New Form</h2>

      {status === 'idle' || status === 'error' ? (
        <>
          <div className="mb-4">
            <label className="block text-sm font-medium mb-1" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>
              Industry *
            </label>
            <select
              value={industry}
              onChange={e => setIndustry(e.target.value)}
              className="w-full p-2 rounded-lg text-sm"
              style={{ border: `1px solid ${colors.border}`, color: colors.textPrimary, backgroundColor: '#fff' }}
            >
              <option value="">Select industry…</option>
              {INDUSTRIES.map(i => (
                <option key={i.value} value={i.value}>{i.label}</option>
              ))}
            </select>
          </div>

          <div className="mb-6">
            <label className="block text-sm font-medium mb-1" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>
              Custom Instructions <span style={{ color: colors.textSecondary }}>(optional)</span>
            </label>
            <textarea
              value={instructions}
              onChange={e => setInstructions(e.target.value)}
              rows={3}
              placeholder="e.g. Add Medicare number and DVA fields, include a K10 psychological distress scale, use plain-English headings…"
              className="w-full p-2 rounded-lg text-sm resize-none"
              style={{ border: `1px solid ${colors.border}`, color: colors.textPrimary }}
            />
          </div>

          {error && (
            <p className="text-sm mb-4 p-3 rounded-lg" style={{ color: '#dc2626', backgroundColor: '#fef2f2' }}>
              {error}
            </p>
          )}

          <button
            onClick={handleGenerate}
            className="w-full py-2 rounded-lg font-medium"
            style={{ backgroundColor: colors.primary, color: '#fff' }}
          >
            Generate My Form
          </button>
        </>
      ) : (
        <div className="p-6 rounded-lg text-center" style={{ border: `1px solid ${colors.border}` }}>
          <div className="mb-4">
            <div
              className="h-2 rounded-full mb-2"
              style={{ backgroundColor: colors.border }}
            >
              <div
                className="h-2 rounded-full transition-all"
                style={{ width: `${progress}%`, backgroundColor: colors.primary }}
              />
            </div>
            <p className="text-sm" style={{ color: colors.textSecondary }}>{progressMsg}</p>
          </div>
          <p className="text-xs" style={{ color: colors.textSecondary }}>
            This usually takes 30–60 seconds…
          </p>
        </div>
      )}
    </div>
  );
}

function PreviewView({
  form,
  onBack,
  onRegenerate,
}: {
  form: GeneratedForm;
  onBack: () => void;
  onRegenerate: () => void;
}) {
  let schema: FormSchema | null = null;
  try {
    if (form.formSchemaJson) schema = JSON.parse(form.formSchemaJson);
  } catch { /* invalid JSON */ }

  return (
    <div>
      <button
        onClick={onBack}
        className="text-sm mb-4 flex items-center gap-1"
        style={{ color: colors.textSecondary }}
      >
        ← Back to Forms
      </button>

      <div className="flex items-start justify-between mb-4">
        <div>
          <h2 className="text-lg font-bold" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>
            {form.formTitle || 'Generated Form'}
          </h2>
          <p className="text-sm" style={{ color: colors.textSecondary }}>
            {INDUSTRIES.find(i => i.value === form.industry)?.label ?? form.industry}
          </p>
        </div>
        <div className="flex items-center gap-2">
          {form.ahpraCompliant === true && (
            <span className="text-xs px-2 py-1 rounded-full font-medium" style={{ backgroundColor: '#dcfce7', color: '#16a34a' }}>
              ✓ AHPRA Compliant
            </span>
          )}
          {form.ahpraCompliant === false && (
            <span className="text-xs px-2 py-1 rounded-full font-medium" style={{ backgroundColor: '#fef2f2', color: '#dc2626' }}>
              ⚠ Review Required
            </span>
          )}
          <button
            onClick={onRegenerate}
            className="text-xs px-3 py-1 rounded-lg"
            style={{ border: `1px solid ${colors.border}`, color: colors.textPrimary }}
          >
            Regenerate
          </button>
        </div>
      </div>

      {form.complianceNotes && (
        <div className="mb-4 p-3 rounded-lg text-sm" style={{ backgroundColor: '#fffbeb', border: `1px solid #fde68a`, color: '#92400e' }}>
          {form.complianceNotes}
        </div>
      )}

      {schema ? (
        <FormPreview schema={schema} />
      ) : (
        <p className="text-sm" style={{ color: colors.textSecondary }}>No preview available.</p>
      )}
    </div>
  );
}

// ─── Branded, type-aware preview ────────────────────────────────────
// Mirror of the Wix and standalone renderers but with WP-plugin styling
// (Tailwind utility classes + inline colour vars). Schema parsing, type
// taxonomy, branded-meta extraction, and footer text all live in
// @formiq/core/forms — change the canonical schema once and every renderer
// (Wix, standalone, WP, Ghost) stays in sync.
//
// `tenant` is optional. Pass it when WP exposes practitioner profile
// data into this view; the branded header degrades gracefully when null.

interface FormPreviewProps {
  schema: unknown;
  tenant?: { practiceName?: string; practitionerName?: string; practitionerId?: string } | null;
  ahpraCompliant?: boolean;
}

const inputClass = "w-full p-2 rounded text-sm";
const inputStyle: React.CSSProperties = {
  border: `1px solid ${colors.border}`,
  backgroundColor: '#f9fafb',
  color: colors.textSecondary,
};

function FormPreview({ schema: rawSchema, tenant, ahpraCompliant }: FormPreviewProps) {
  const schema = parseFormSchema(rawSchema);
  if (!schema) {
    return (
      <div className="p-4 rounded-lg bg-white text-sm" style={{ border: `1px solid ${colors.border}`, color: colors.textSecondary }}>
        No preview available.
      </div>
    );
  }
  const meta = extractBrandedMeta(schema, tenant, undefined, ahpraCompliant ?? false);

  return (
    <div className="rounded-lg overflow-hidden" style={{ border: `1px solid ${colors.border}`, backgroundColor: '#FFFFFF' }}>
      {/* Branded header — same intent as the Wix / standalone renderers */}
      <div
        className="px-6 pt-6 pb-5"
        style={{
          background: 'linear-gradient(180deg, #FAFAFC 0%, #FFFFFF 100%)',
          borderBottom: `4px solid ${colors.primary}`,
        }}
      >
        {meta.practiceName && (
          <div className="text-xl font-bold tracking-tight" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>
            {meta.practiceName}
          </div>
        )}
        <div className="text-base font-bold mt-2" style={{ color: colors.primary, fontFamily: fonts.heading }}>
          {meta.formTitle}
        </div>
        {meta.formDescription && (
          <p className="text-sm mt-2 leading-relaxed" style={{ color: colors.textSecondary }}>
            {meta.formDescription}
          </p>
        )}
        {(meta.practitionerName || meta.practitionerId) && (
          <div className="text-xs mt-3" style={{ color: colors.textSecondary }}>
            <strong style={{ color: colors.textPrimary }}>{meta.practitionerName}</strong>
            {meta.practitionerId ? ` · Reg. ${meta.practitionerId}` : ''}
          </div>
        )}
      </div>

      <div className="px-6 py-6 grid gap-7">
        {schema.sections.map((section, si) => (
          <div key={si}>
            <div className="flex items-center gap-3 mb-3">
              <span
                className="inline-flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold"
                style={{ backgroundColor: colors.primary, color: '#fff' }}
              >{si + 1}</span>
              <h4 className="text-sm font-bold m-0" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>
                {section.title}
              </h4>
            </div>
            {section.description && (
              <p className="text-xs mb-3 ml-9" style={{ color: colors.textSecondary }}>{section.description}</p>
            )}
            <div className="grid gap-4 pl-9">
              {section.questions.map((q, qi) => <QuestionPreview key={qi} q={q} />)}
            </div>
          </div>
        ))}
      </div>

      {meta.practiceName && (
        <div className="px-6 py-4" style={{ backgroundColor: '#FAFAFC', borderTop: `1px solid ${colors.border}` }}>
          <p className="text-xs m-0 leading-relaxed" style={{ color: colors.textSecondary }}>
            {privacyFooterText(meta.practiceName)}
          </p>
        </div>
      )}
    </div>
  );
}

function QuestionPreview({ q }: { q: FormQuestion }) {
  const hint = renderHintForType(q.type);
  const placeholder = q.placeholder ?? hint.defaultPlaceholder;
  const required = q.required ? <span style={{ color: '#dc2626' }}> *</span> : null;
  const options = q.options ?? [];

  // Consent and signature own the row — question text IS the binding statement.
  if (hint.kind === 'consent') {
    return (
      <label className="flex items-start gap-2 text-sm leading-relaxed" style={{ color: colors.textPrimary }}>
        <input type="checkbox" disabled className="mt-1" />
        <span>{q.text}{required}</span>
      </label>
    );
  }

  if (hint.kind === 'signature') {
    return (
      <div className="p-4 rounded-lg" style={{ border: `1px solid ${colors.primary}`, backgroundColor: '#F5F3FF' }}>
        <label className="block text-xs font-semibold mb-2" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>
          {q.text || 'Signature — type your full legal name'}{required}
        </label>
        <input type="text" placeholder={placeholder} disabled className={`${inputClass} text-base`} style={inputStyle} />
        <p className="text-xs mt-2 m-0" style={{ color: colors.textSecondary }}>
          {q.helpText ?? 'By typing your full legal name, you formally sign and agree to the information above.'}
        </p>
      </div>
    );
  }

  return (
    <div>
      <label className="block text-xs font-medium mb-1" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>
        {q.text}{required}
      </label>
      {hint.kind === 'multi-line' && (
        <textarea disabled rows={3} placeholder={placeholder} className={`${inputClass} resize-y`} style={inputStyle} />
      )}
      {hint.kind === 'choice-select' && (
        <select disabled className={inputClass} style={inputStyle}>
          <option>{placeholder ?? 'Select an option…'}</option>
          {options.map((opt, i) => <option key={i}>{opt}</option>)}
        </select>
      )}
      {hint.kind === 'choice-radio' && (
        <div className="grid gap-1">
          {options.map((opt, i) => (
            <label key={i} className="flex items-center gap-2 text-sm" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>
              <input type="radio" disabled /> {opt}
            </label>
          ))}
        </div>
      )}
      {hint.kind === 'choice-multi' && (
        <div className="grid gap-1">
          {options.map((opt, i) => (
            <label key={i} className="flex items-center gap-2 text-sm" style={{ color: colors.textPrimary, fontFamily: fonts.heading }}>
              <input type="checkbox" disabled /> {opt}
            </label>
          ))}
        </div>
      )}
      {hint.kind === 'scale-1-10' && (
        <div>
          <input type="range" min={1} max={10} step={1} defaultValue={5} disabled className="w-full" />
          <div className="flex justify-between text-xs" style={{ color: colors.textSecondary }}>
            <span>1 — Lowest</span><span>10 — Highest</span>
          </div>
        </div>
      )}
      {hint.kind === 'date' && (
        <input type="date" disabled className="p-2 rounded text-sm" style={inputStyle} />
      )}
      {hint.kind === 'single-line' && (
        <input type="text" placeholder={placeholder} disabled className={inputClass} style={inputStyle} />
      )}
      {q.helpText && (
        <p className="text-xs mt-1 m-0" style={{ color: colors.textSecondary }}>{q.helpText}</p>
      )}
    </div>
  );
}

function sleep(ms: number) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
