/**
 * @file Intake Form MCP App — collects company info, competitors, and research focus areas.
 * Pattern 1: All form state is client-side. On submit, sends a ResearchBrief to the host.
 */
import type { McpUiHostContext } from "@modelcontextprotocol/ext-apps";
import { useApp, useHostStyles } from "@modelcontextprotocol/ext-apps/react";
import {
  useState,
  useCallback,
  useEffect,
  type KeyboardEvent,
  type ChangeEvent,
  type CSSProperties,
  type ReactNode,
} from "react";
import type {
  CompanyProfile,
  CompetitorEntry,
  FocusArea,
  ResearchBrief,
} from "../../types";

/* ------------------------------------------------------------------ */
/*  Constants                                                          */
/* ------------------------------------------------------------------ */

const INDUSTRIES = [
  "SaaS",
  "E-commerce",
  "Agency",
  "Fintech",
  "Healthcare",
  "Education",
  "Other",
] as const;

const FOCUS_OPTIONS: { value: Exclude<FocusArea, "all">; label: string }[] = [
  { value: "pricing", label: "Pricing" },
  { value: "features", label: "Features" },
  { value: "content", label: "Content Strategy" },
  { value: "social", label: "Social Presence" },
  { value: "seo", label: "SEO" },
];

const MAX_COMPETITORS = 10;

const emptyCompetitor = (): CompetitorEntry => ({ name: "", url: "", notes: "" });

/* ------------------------------------------------------------------ */
/*  Styles                                                             */
/* ------------------------------------------------------------------ */

const css = {
  root: {
    fontFamily: "var(--font-sans, system-ui, -apple-system, sans-serif)",
    color: "var(--color-text-primary, #1a1a2e)",
    background: "var(--color-background-primary, #ffffff)",
    maxWidth: 640,
    margin: "0 auto",
    padding: "24px 20px 40px",
    lineHeight: 1.5,
  } as CSSProperties,

  heading: {
    fontSize: 22,
    fontWeight: 700,
    marginBottom: 4,
    color: "var(--color-text-primary, #1a1a2e)",
  } as CSSProperties,

  subtitle: {
    fontSize: 14,
    color: "var(--color-text-secondary, #64748b)",
    marginBottom: 28,
  } as CSSProperties,

  section: {
    background: "var(--color-background-secondary, #f8fafc)",
    border: "1px solid var(--color-border-primary, #e2e8f0)",
    borderRadius: 12,
    padding: "20px 20px 24px",
    marginBottom: 20,
  } as CSSProperties,

  sectionTitle: {
    fontSize: 15,
    fontWeight: 600,
    color: "var(--color-text-primary, #1a1a2e)",
    marginBottom: 16,
    display: "flex",
    alignItems: "center",
    gap: 8,
  } as CSSProperties,

  label: {
    display: "block",
    fontSize: 13,
    fontWeight: 500,
    color: "var(--color-text-secondary, #475569)",
    marginBottom: 5,
  } as CSSProperties,

  input: {
    width: "100%",
    padding: "9px 12px",
    fontSize: 14,
    fontFamily: "inherit",
    border: "1px solid var(--color-border-primary, #e2e8f0)",
    borderRadius: 8,
    background: "var(--color-background-primary, #ffffff)",
    color: "var(--color-text-primary, #1a1a2e)",
    outline: "none",
    transition: "border-color 0.15s, box-shadow 0.15s",
    boxSizing: "border-box" as const,
  } as CSSProperties,

  inputFocus: {
    borderColor: "#3b82f6",
    boxShadow: "0 0 0 3px rgba(59,130,246,0.15)",
  } as CSSProperties,

  textarea: {
    resize: "vertical" as const,
    minHeight: 64,
  } as CSSProperties,

  select: {
    appearance: "none" as const,
    backgroundImage:
      "url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e\")",
    backgroundRepeat: "no-repeat",
    backgroundPosition: "right 10px center",
    backgroundSize: 16,
    paddingRight: 32,
  } as CSSProperties,

  fieldGroup: {
    marginBottom: 14,
  } as CSSProperties,

  row: {
    display: "grid",
    gridTemplateColumns: "1fr 1fr",
    gap: 12,
  } as CSSProperties,

  /* Tags (value propositions) */
  tagContainer: {
    display: "flex",
    flexWrap: "wrap" as const,
    gap: 6,
    marginTop: 8,
  } as CSSProperties,

  tag: {
    display: "inline-flex",
    alignItems: "center",
    gap: 4,
    padding: "4px 10px",
    fontSize: 13,
    fontWeight: 500,
    background: "#dbeafe",
    color: "#1e40af",
    borderRadius: 999,
    cursor: "pointer",
    transition: "background 0.15s, transform 0.1s",
    border: "none",
    fontFamily: "inherit",
  } as CSSProperties,

  tagX: {
    fontSize: 14,
    fontWeight: 600,
    lineHeight: 1,
    opacity: 0.6,
  } as CSSProperties,

  /* Competitor cards */
  competitorCard: {
    border: "1px solid var(--color-border-primary, #e2e8f0)",
    borderRadius: 10,
    padding: 16,
    marginBottom: 12,
    background: "var(--color-background-primary, #ffffff)",
    position: "relative" as const,
    transition: "box-shadow 0.2s, opacity 0.3s",
  } as CSSProperties,

  competitorHeader: {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 12,
  } as CSSProperties,

  competitorNum: {
    fontSize: 13,
    fontWeight: 600,
    color: "#3b82f6",
  } as CSSProperties,

  removeBtn: {
    background: "none",
    border: "none",
    fontSize: 18,
    color: "var(--color-text-secondary, #94a3b8)",
    cursor: "pointer",
    padding: "2px 6px",
    borderRadius: 6,
    transition: "color 0.15s, background 0.15s",
    lineHeight: 1,
  } as CSSProperties,

  addBtn: {
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
    padding: "8px 16px",
    fontSize: 13,
    fontWeight: 600,
    color: "#3b82f6",
    background: "#eff6ff",
    border: "1px dashed #93c5fd",
    borderRadius: 8,
    cursor: "pointer",
    transition: "background 0.15s",
    fontFamily: "inherit",
  } as CSSProperties,

  /* Focus area checkboxes */
  checkboxGrid: {
    display: "grid",
    gridTemplateColumns: "1fr 1fr",
    gap: "10px 16px",
  } as CSSProperties,

  checkboxLabel: {
    display: "flex",
    alignItems: "center",
    gap: 8,
    fontSize: 14,
    color: "var(--color-text-primary, #334155)",
    cursor: "pointer",
    padding: "6px 10px",
    borderRadius: 8,
    transition: "background 0.12s",
    border: "1px solid transparent",
  } as CSSProperties,

  checkboxLabelActive: {
    background: "#eff6ff",
    borderColor: "#bfdbfe",
  } as CSSProperties,

  checkbox: {
    width: 16,
    height: 16,
    accentColor: "#3b82f6",
    cursor: "pointer",
  } as CSSProperties,

  selectAllRow: {
    display: "flex",
    justifyContent: "flex-end",
    marginBottom: 10,
  } as CSSProperties,

  selectAllBtn: {
    fontSize: 12,
    fontWeight: 600,
    color: "#3b82f6",
    background: "none",
    border: "none",
    cursor: "pointer",
    padding: "2px 6px",
    fontFamily: "inherit",
    textDecoration: "underline",
    textUnderlineOffset: 2,
  } as CSSProperties,

  /* Submit */
  submitBtn: {
    width: "100%",
    padding: "14px 24px",
    fontSize: 15,
    fontWeight: 700,
    color: "#ffffff",
    background: "linear-gradient(135deg, #3b82f6, #2563eb)",
    border: "none",
    borderRadius: 10,
    cursor: "pointer",
    transition: "transform 0.12s, box-shadow 0.2s",
    boxShadow: "0 2px 8px rgba(37,99,235,0.3)",
    fontFamily: "inherit",
    letterSpacing: 0.2,
  } as CSSProperties,

  submitBtnDisabled: {
    opacity: 0.5,
    cursor: "not-allowed",
    boxShadow: "none",
  } as CSSProperties,

  hint: {
    fontSize: 12,
    color: "var(--color-text-secondary, #94a3b8)",
    marginTop: 4,
  } as CSSProperties,

  error: {
    fontSize: 13,
    color: "#ef4444",
    marginTop: 6,
  } as CSSProperties,

  badge: {
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
    minWidth: 20,
    height: 20,
    padding: "0 6px",
    fontSize: 11,
    fontWeight: 700,
    borderRadius: 999,
    background: "#3b82f6",
    color: "#fff",
  } as CSSProperties,
} as const;

/* ------------------------------------------------------------------ */
/*  Small components                                                   */
/* ------------------------------------------------------------------ */

function FocusInput({
  value,
  onChange,
  ...props
}: {
  value: string;
  onChange: (v: string) => void;
  [k: string]: unknown;
}) {
  const [focused, setFocused] = useState(false);
  return (
    <input
      {...(props as React.InputHTMLAttributes<HTMLInputElement>)}
      value={value}
      onChange={(e: ChangeEvent<HTMLInputElement>) => onChange(e.target.value)}
      onFocus={() => setFocused(true)}
      onBlur={() => setFocused(false)}
      style={{ ...css.input, ...(focused ? css.inputFocus : {}), ...(props.style as CSSProperties) }}
    />
  );
}

function FocusTextarea({
  value,
  onChange,
  ...props
}: {
  value: string;
  onChange: (v: string) => void;
  rows?: number;
  placeholder?: string;
  style?: CSSProperties;
}) {
  const [focused, setFocused] = useState(false);
  return (
    <textarea
      {...props}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      onFocus={() => setFocused(true)}
      onBlur={() => setFocused(false)}
      style={{
        ...css.input,
        ...css.textarea,
        ...(focused ? css.inputFocus : {}),
        ...(props.style ?? {}),
      }}
    />
  );
}

function Section({ icon, title, children }: { icon: string; title: string; children: ReactNode }) {
  return (
    <div style={css.section}>
      <div style={css.sectionTitle}>
        <span>{icon}</span> {title}
      </div>
      {children}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Main App                                                           */
/* ------------------------------------------------------------------ */

export function IntakeFormApp() {
  const [hostContext, setHostContext] = useState<McpUiHostContext | undefined>();
  const [submitted, setSubmitted] = useState(false);

  const { app, error } = useApp({
    appInfo: { name: "Competitor Research — Intake", version: "1.0.0" },
    capabilities: {},
    onAppCreated: (app) => {
      app.onerror = console.error;
      app.onhostcontextchanged = (params) => {
        setHostContext((prev) => ({ ...prev, ...params }));
      };
    },
  });

  useHostStyles(app, app?.getHostContext());

  useEffect(() => {
    if (app) setHostContext(app.getHostContext());
  }, [app]);

  /* ---- Form state ---- */
  const [name, setName] = useState("");
  const [url, setUrl] = useState("");
  const [industry, setIndustry] = useState("");
  const [customIndustry, setCustomIndustry] = useState("");
  const [description, setDescription] = useState("");
  const [valueProps, setValueProps] = useState<string[]>([]);
  const [vpInput, setVpInput] = useState("");

  const [competitors, setCompetitors] = useState<CompetitorEntry[]>([emptyCompetitor()]);

  const allFocus: Exclude<FocusArea, "all">[] = ["pricing", "features", "content", "social", "seo"];
  const [focusAreas, setFocusAreas] = useState<Set<Exclude<FocusArea, "all">>>(new Set(allFocus));

  /* ---- Handlers ---- */

  const handleVpKeyDown = useCallback(
    (e: KeyboardEvent<HTMLInputElement>) => {
      if (e.key === "Enter" && vpInput.trim()) {
        e.preventDefault();
        const tag = vpInput.trim();
        if (!valueProps.includes(tag)) {
          setValueProps((prev) => [...prev, tag]);
        }
        setVpInput("");
      }
    },
    [vpInput, valueProps]
  );

  const removeVp = useCallback((tag: string) => {
    setValueProps((prev) => prev.filter((t) => t !== tag));
  }, []);

  const updateCompetitor = useCallback((idx: number, patch: Partial<CompetitorEntry>) => {
    setCompetitors((prev) => prev.map((c, i) => (i === idx ? { ...c, ...patch } : c)));
  }, []);

  const addCompetitor = useCallback(() => {
    setCompetitors((prev) => (prev.length < MAX_COMPETITORS ? [...prev, emptyCompetitor()] : prev));
  }, []);

  const removeCompetitor = useCallback((idx: number) => {
    setCompetitors((prev) => (prev.length > 1 ? prev.filter((_, i) => i !== idx) : prev));
  }, []);

  const toggleFocus = useCallback((area: Exclude<FocusArea, "all">) => {
    setFocusAreas((prev) => {
      const next = new Set(prev);
      next.has(area) ? next.delete(area) : next.add(area);
      return next;
    });
  }, []);

  const toggleAll = useCallback(() => {
    setFocusAreas((prev) => (prev.size === allFocus.length ? new Set() : new Set(allFocus)));
  }, [allFocus]);

  /* ---- Validation ---- */
  const resolvedIndustry = industry === "Other" ? customIndustry.trim() : industry;
  const validCompetitors = competitors.filter((c) => c.name.trim() && c.url.trim());
  const canSubmit =
    name.trim() !== "" &&
    url.trim() !== "" &&
    resolvedIndustry !== "" &&
    validCompetitors.length > 0 &&
    focusAreas.size > 0 &&
    !submitted;

  /* ---- Submit ---- */
  const handleSubmit = useCallback(async () => {
    if (!app || !canSubmit) return;
    setSubmitted(true);

    const brief: ResearchBrief = {
      company: {
        name: name.trim(),
        url: url.trim(),
        industry: resolvedIndustry,
        description: description.trim(),
        valueProps,
      } satisfies CompanyProfile,
      competitors: validCompetitors.map((c) => ({
        name: c.name.trim(),
        url: c.url.trim(),
        ...(c.notes?.trim() ? { notes: c.notes.trim() } : {}),
      })),
      focusAreas: focusAreas.size === allFocus.length ? ["all"] : [...focusAreas],
    };

    try {
      await app.sendMessage(
        {
          role: "user",
          content: [
            {
              type: "text",
              text: `Please analyze these competitors:\n\n${JSON.stringify(brief, null, 2)}`,
            },
          ],
        },
        { signal: AbortSignal.timeout(10_000) }
      );
    } catch (e) {
      console.error("Failed to send message:", e);
      setSubmitted(false);
    }
  }, [app, canSubmit, name, url, resolvedIndustry, description, valueProps, validCompetitors, focusAreas, allFocus]);

  /* ---- Render states ---- */
  if (error) {
    return (
      <div style={{ ...css.root, textAlign: "center", paddingTop: 60 }}>
        <p style={{ color: "#ef4444", fontWeight: 600 }}>Connection Error</p>
        <p style={{ color: "var(--color-text-secondary, #64748b)", fontSize: 13 }}>{error.message}</p>
      </div>
    );
  }

  if (!app) {
    return (
      <div style={{ ...css.root, textAlign: "center", paddingTop: 60 }}>
        <p style={{ color: "var(--color-text-secondary, #64748b)" }}>Connecting…</p>
      </div>
    );
  }

  if (submitted) {
    return (
      <div style={{ ...css.root, textAlign: "center", paddingTop: 60 }}>
        <div style={{ fontSize: 40, marginBottom: 12 }}>🚀</div>
        <p style={{ fontSize: 18, fontWeight: 700, marginBottom: 6 }}>Research Initiated!</p>
        <p style={{ fontSize: 14, color: "var(--color-text-secondary, #64748b)" }}>
          Analyzing {validCompetitors.length} competitor{validCompetitors.length !== 1 ? "s" : ""} for{" "}
          <strong>{name}</strong>. Results will appear shortly.
        </p>
      </div>
    );
  }

  const insets = hostContext?.safeAreaInsets;

  return (
    <div
      style={{
        ...css.root,
        paddingTop: (insets?.top ?? 0) + 24,
        paddingRight: (insets?.right ?? 0) + 20,
        paddingBottom: (insets?.bottom ?? 0) + 40,
        paddingLeft: (insets?.left ?? 0) + 20,
      }}
    >
      <div style={css.heading}>Competitor Research</div>
      <p style={css.subtitle}>Fill in your company details and competitors to start the analysis.</p>

      {/* ── Your Company ── */}
      <Section icon="🏢" title="Your Company">
        <div style={css.row}>
          <div style={css.fieldGroup}>
            <label style={css.label}>Company Name *</label>
            <FocusInput value={name} onChange={setName} placeholder="Acme Inc." />
          </div>
          <div style={css.fieldGroup}>
            <label style={css.label}>Website URL *</label>
            <FocusInput value={url} onChange={setUrl} type="url" placeholder="https://acme.com" />
          </div>
        </div>

        <div style={css.row}>
          <div style={css.fieldGroup}>
            <label style={css.label}>Industry *</label>
            <select
              value={industry}
              onChange={(e) => setIndustry(e.target.value)}
              style={{ ...css.input, ...css.select }}
            >
              <option value="">Select…</option>
              {INDUSTRIES.map((ind) => (
                <option key={ind} value={ind}>
                  {ind}
                </option>
              ))}
            </select>
          </div>
          {industry === "Other" && (
            <div style={css.fieldGroup}>
              <label style={css.label}>Specify Industry *</label>
              <FocusInput value={customIndustry} onChange={setCustomIndustry} placeholder="e.g. Logistics" />
            </div>
          )}
        </div>

        <div style={css.fieldGroup}>
          <label style={css.label}>Description</label>
          <FocusTextarea
            value={description}
            onChange={setDescription}
            rows={2}
            placeholder="Brief description of what your company does…"
          />
        </div>

        <div style={css.fieldGroup}>
          <label style={css.label}>Value Propositions</label>
          <FocusInput
            value={vpInput}
            onChange={setVpInput}
            placeholder="Type a value prop and press Enter"
            onKeyDown={handleVpKeyDown}
          />
          <p style={css.hint}>Press Enter to add, click a tag to remove</p>
          {valueProps.length > 0 && (
            <div style={css.tagContainer}>
              {valueProps.map((tag) => (
                <button
                  key={tag}
                  style={css.tag}
                  onClick={() => removeVp(tag)}
                  title="Click to remove"
                >
                  {tag} <span style={css.tagX}>×</span>
                </button>
              ))}
            </div>
          )}
        </div>
      </Section>

      {/* ── Competitors ── */}
      <Section icon="🎯" title="Competitors">
        {competitors.map((comp, idx) => (
          <div key={idx} style={css.competitorCard}>
            <div style={css.competitorHeader}>
              <span style={css.competitorNum}>Competitor {idx + 1}</span>
              {competitors.length > 1 && (
                <button
                  style={css.removeBtn}
                  onClick={() => removeCompetitor(idx)}
                  title="Remove competitor"
                  onMouseEnter={(e) => {
                    (e.currentTarget.style.color = "#ef4444");
                    (e.currentTarget.style.background = "#fef2f2");
                  }}
                  onMouseLeave={(e) => {
                    (e.currentTarget.style.color = "var(--color-text-secondary, #94a3b8)");
                    (e.currentTarget.style.background = "none");
                  }}
                >
                  ✕
                </button>
              )}
            </div>
            <div style={css.row}>
              <div style={css.fieldGroup}>
                <label style={css.label}>Name *</label>
                <FocusInput
                  value={comp.name}
                  onChange={(v: string) => updateCompetitor(idx, { name: v })}
                  placeholder="Competitor name"
                />
              </div>
              <div style={css.fieldGroup}>
                <label style={css.label}>URL *</label>
                <FocusInput
                  value={comp.url}
                  onChange={(v: string) => updateCompetitor(idx, { url: v })}
                  type="url"
                  placeholder="https://…"
                />
              </div>
            </div>
            <div style={css.fieldGroup}>
              <label style={css.label}>Notes (optional)</label>
              <FocusTextarea
                value={comp.notes ?? ""}
                onChange={(v: string) => updateCompetitor(idx, { notes: v })}
                rows={1}
                placeholder="Anything specific to research about this competitor?"
                style={{ minHeight: 40 }}
              />
            </div>
          </div>
        ))}
        {competitors.length < MAX_COMPETITORS && (
          <button
            style={css.addBtn}
            onClick={addCompetitor}
            onMouseEnter={(e) => (e.currentTarget.style.background = "#dbeafe")}
            onMouseLeave={(e) => (e.currentTarget.style.background = "#eff6ff")}
          >
            <span style={{ fontSize: 16 }}>＋</span> Add Competitor
          </button>
        )}
        {competitors.length >= MAX_COMPETITORS && (
          <p style={css.hint}>Maximum of {MAX_COMPETITORS} competitors reached.</p>
        )}
      </Section>

      {/* ── Research Focus ── */}
      <Section icon="🔍" title="Research Focus">
        <div style={css.selectAllRow}>
          <button style={css.selectAllBtn} onClick={toggleAll}>
            {focusAreas.size === allFocus.length ? "Deselect All" : "Select All"}
          </button>
        </div>
        <div style={css.checkboxGrid}>
          {FOCUS_OPTIONS.map(({ value, label }) => {
            const active = focusAreas.has(value);
            return (
              <label
                key={value}
                style={{
                  ...css.checkboxLabel,
                  ...(active ? css.checkboxLabelActive : {}),
                }}
              >
                <input
                  type="checkbox"
                  checked={active}
                  onChange={() => toggleFocus(value)}
                  style={css.checkbox}
                />
                {label}
              </label>
            );
          })}
        </div>
      </Section>

      {/* ── Submit ── */}
      <button
        style={{
          ...css.submitBtn,
          ...(!canSubmit ? css.submitBtnDisabled : {}),
        }}
        onClick={handleSubmit}
        disabled={!canSubmit}
        onMouseEnter={(e) => {
          if (canSubmit) {
            e.currentTarget.style.transform = "translateY(-1px)";
            e.currentTarget.style.boxShadow = "0 4px 14px rgba(37,99,235,0.4)";
          }
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.transform = "none";
          e.currentTarget.style.boxShadow = canSubmit ? "0 2px 8px rgba(37,99,235,0.3)" : "none";
        }}
      >
        🚀&nbsp; Start Research
      </button>

      {!canSubmit && name.trim() && (
        <p style={css.error}>
          {!url.trim()
            ? "Please enter your website URL."
            : !resolvedIndustry
              ? "Please select an industry."
              : validCompetitors.length === 0
                ? "Add at least one competitor with name and URL."
                : focusAreas.size === 0
                  ? "Select at least one research focus area."
                  : ""}
        </p>
      )}
    </div>
  );
}
