"use client";

import { useRouter } from "next/navigation";
import { FormEvent, useMemo, useState } from "react";
import { SamGovIntegrationCard } from "@/components/settings/sam-gov-integration-card";
import { BUSINESS_TYPES, REVENUE_RANGES, USER_ROLE_TITLES } from "@/lib/constants";
import {
  TAXONOMY_CATEGORIES,
  getBusinessTypesForCategory,
  getPriorityIndustries,
  resolveIndustrySelection,
} from "@/lib/business-roles-taxonomy";
import { buildBusinessProfile } from "@/lib/business-brain";
import {
  generateAiSummary,
  generateMockBrandScore,
  generateMockCompetitors,
  generateMockOpportunities,
  generateMockRecommendations,
} from "@/lib/mock-data";
import type { Business, OnboardingInput } from "@/lib/types";
import { saveBusiness } from "@/lib/data-store";
import { applyLiveBidsToBusiness, fetchLiveFederalBids } from "@/lib/federal-work/fetch-live-bids";
import { enrichBusinessWithRoles } from "@/lib/role-intelligence";
import { resolveUserRole } from "@/lib/user-workplace-role";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";

const defaultCategory = TAXONOMY_CATEGORIES[0] ?? "Healthcare";
const defaultSubtype = getBusinessTypesForCategory(defaultCategory)[0]?.label ?? "Physicians";
const defaultResolved = resolveIndustrySelection(defaultCategory, defaultSubtype);

const defaultInput: OnboardingInput = {
  businessName: "",
  websiteUrl: "",
  industryCategory: defaultCategory,
  industry: defaultResolved?.industry ?? "Medical Practice",
  businessSubtype: defaultSubtype,
  location: "",
  businessType: BUSINESS_TYPES[0],
  monthlyRevenueRange: REVENUE_RANGES[1],
  revenueGoal: "",
  biggestChallenge: "",
  productsServices: "",
  mainCompetitors: "",
  targetCustomer: "",
};

export default function OnboardingPage() {
  const router = useRouter();
  const [step, setStep] = useState(1);
  const [form, setForm] = useState<OnboardingInput>(defaultInput);
  const [userRoleTitle, setUserRoleTitle] = useState(USER_ROLE_TITLES[0]);
  const [aiLeaderEnabled, setAiLeaderEnabled] = useState(false);
  const [loading, setLoading] = useState(false);
  const [businessDraft, setBusinessDraft] = useState<Business | null>(null);
  const [platformFetchNote, setPlatformFetchNote] = useState<string | null>(null);

  const businessTypes = useMemo(
    () => getBusinessTypesForCategory(form.industryCategory),
    [form.industryCategory],
  );

  const priorityIds = useMemo(() => {
    const set = new Set<string>();
    for (const p of getPriorityIndustries()) {
      for (const link of p.linkedBusinessTypes) set.add(link.industryId);
    }
    return set;
  }, []);

  const canContinue = useMemo(() => {
    if (step === 1) {
      return Boolean(form.businessName && form.industryCategory && form.industry && form.location);
    }
    if (step === 2) return Boolean(form.businessType && form.monthlyRevenueRange && form.revenueGoal);
    return Boolean(form.biggestChallenge && form.productsServices && form.targetCustomer);
  }, [step, form]);

  const setCategory = (category: string) => {
    const types = getBusinessTypesForCategory(category);
    const first = types[0];
    const resolved = first ? resolveIndustrySelection(category, first.label) : null;
    setForm((p) => ({
      ...p,
      industryCategory: category,
      businessSubtype: first?.label,
      industry: resolved?.industry ?? p.industry,
    }));
  };

  const setSubtype = (label: string) => {
    const resolved = resolveIndustrySelection(form.industryCategory, label);
    setForm((p) => ({
      ...p,
      businessSubtype: label,
      industry: resolved?.industry ?? p.industry,
    }));
  };

  const completeOnboarding = async (e: FormEvent) => {
    e.preventDefault();
    setLoading(true);

    const profile = buildBusinessProfile(form);
    const opportunities = generateMockOpportunities(form, profile);
    const competitors = generateMockCompetitors(profile);
    const recommendations = generateMockRecommendations(form, opportunities);
    const brandScore = generateMockBrandScore(form);
    const revenuePotential = opportunities.reduce((s, o) => s + o.estimatedValue, 0);
    const topPriority = opportunities.sort((a, b) => b.urgencyScore - a.urgencyScore)[0];

    let business: Business = enrichBusinessWithRoles({
      id: crypto.randomUUID(),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      input: form,
      profile,
      opportunities,
      competitors,
      recommendations,
      brandScore,
      metrics: {
        opportunitiesFound: opportunities.length,
        recommendedActions: recommendations.length,
        revenuePotential,
        topPriorityToday: topPriority?.title ?? "Complete your first opportunity",
      },
      aiSummary: generateAiSummary(form, opportunities),
      userRole: {
        title: userRoleTitle,
        aiLeaderEnabled,
      },
    });

    // Try platform SAM key (server env) for instant live bids before user connects their own
    try {
      const bidData = await fetchLiveFederalBids(business);
      if (bidData.ok && bidData.opportunities && (bidData.imported ?? 0) > 0) {
        business = applyLiveBidsToBusiness(business, bidData.opportunities, { imported: bidData.imported });
        setPlatformFetchNote(`Pre-loaded ${bidData.imported} live federal bids matched to your business.`);
      }
    } catch {
      /* platform key optional */
    }

    await saveBusiness(business);
    setBusinessDraft(business);
    setStep(4);
    setLoading(false);
  };

  const finishOnboarding = async (destination: "/dashboard" | "/opportunities") => {
    if (businessDraft) await saveBusiness(businessDraft);
    router.push(destination);
  };

  return (
    <div className="mx-auto max-w-3xl py-8">
      <Card>
        <CardHeader>
          <CardTitle>Build your Business Brain</CardTitle>
          <CardDescription>
            {step <= 3
              ? `Step ${step} of 4 — BrandLxft learns your company so your AI co-founder can find opportunities and tell you what to do next.`
              : "Step 4 of 4 — Connect SAM.gov to pull live federal bids automatically."}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={completeOnboarding} className="space-y-4">
            {step === 1 && (
              <>
                <Input placeholder="Business name" value={form.businessName} onChange={(e) => setForm((p) => ({ ...p, businessName: e.target.value }))} required />
                <Input placeholder="Website URL" value={form.websiteUrl} onChange={(e) => setForm((p) => ({ ...p, websiteUrl: e.target.value }))} />
                <Select value={form.industryCategory} onChange={(e) => setCategory(e.target.value)}>
                  {TAXONOMY_CATEGORIES.map((c) => (
                    <option key={c} value={c}>{c}</option>
                  ))}
                </Select>
                <Select
                  value={form.businessSubtype ?? businessTypes[0]?.label ?? ""}
                  onChange={(e) => setSubtype(e.target.value)}
                >
                  {businessTypes.map((t) => (
                    <option key={t.slug} value={t.label}>
                      {t.label}{t.isPriority ? " ★" : ""}
                    </option>
                  ))}
                </Select>
                <p className="text-xs text-slate-500">
                  Industry profile: {form.industry}
                  {form.businessSubtype && priorityIds.has(
                    businessTypes.find((b) => b.label === form.businessSubtype)?.industryId ?? "",
                  )
                    ? " · High-growth vertical for BrandLxft"
                    : ""}
                </p>
                <Input placeholder="Location (city, region)" value={form.location} onChange={(e) => setForm((p) => ({ ...p, location: e.target.value }))} required />
              </>
            )}

            {step === 2 && (
              <>
                <Select value={form.businessType} onChange={(e) => setForm((p) => ({ ...p, businessType: e.target.value }))}>
                  {BUSINESS_TYPES.map((t) => (
                    <option key={t} value={t}>{t}</option>
                  ))}
                </Select>
                <Select value={form.monthlyRevenueRange} onChange={(e) => setForm((p) => ({ ...p, monthlyRevenueRange: e.target.value }))}>
                  {REVENUE_RANGES.map((r) => (
                    <option key={r} value={r}>{r}</option>
                  ))}
                </Select>
                <Input placeholder="Revenue goal (e.g. $30K/mo in 6 months)" value={form.revenueGoal} onChange={(e) => setForm((p) => ({ ...p, revenueGoal: e.target.value }))} required />
              </>
            )}

            {step === 3 && (
              <>
                <Textarea placeholder="Biggest challenge right now" value={form.biggestChallenge} onChange={(e) => setForm((p) => ({ ...p, biggestChallenge: e.target.value }))} required />
                <Textarea placeholder="Top products / services" value={form.productsServices} onChange={(e) => setForm((p) => ({ ...p, productsServices: e.target.value }))} required />
                <Input placeholder="Main competitors (optional, comma separated)" value={form.mainCompetitors} onChange={(e) => setForm((p) => ({ ...p, mainCompetitors: e.target.value }))} />
                <Textarea placeholder="Target customer" value={form.targetCustomer} onChange={(e) => setForm((p) => ({ ...p, targetCustomer: e.target.value }))} required />
                <div className="rounded-xl border border-slate-800 p-4 space-y-3">
                  <p className="text-sm font-medium text-slate-200">Your role in the company</p>
                  <Select value={userRoleTitle} onChange={(e) => setUserRoleTitle(e.target.value)}>
                    {USER_ROLE_TITLES.map((title) => (
                      <option key={title} value={title}>{title}</option>
                    ))}
                  </Select>
                  <label className="flex cursor-pointer items-start gap-3">
                    <input
                      type="checkbox"
                      className="mt-1"
                      checked={aiLeaderEnabled}
                      onChange={(e) => setAiLeaderEnabled(e.target.checked)}
                    />
                    <span className="text-sm text-slate-400">
                      <span className="block font-medium text-slate-200">Enable AI Leader</span>
                      Need a boss to get going? BrandLxft will drive priorities, assign role agents, and hold you accountable.
                    </span>
                  </label>
                </div>
              </>
            )}

            {step === 4 && businessDraft ? (
              <div className="space-y-4">
                {platformFetchNote ? (
                  <p className="rounded-lg border border-emerald-500/20 bg-emerald-500/5 p-3 text-sm text-emerald-300">
                    {platformFetchNote}
                  </p>
                ) : null}
                <p className="text-sm text-slate-400">
                  Most owners never discover federal contracting. Connect your SAM.gov API key once and BrandLxft
                  keeps matched open bids in your pipeline — landscaping, plumbing, HVAC, IT, and more.
                </p>
                <SamGovIntegrationCard
                  business={businessDraft}
                  variant="onboarding"
                  autoFetchOnConnect
                  onUpdate={(next) => {
                    setBusinessDraft(next);
                    saveBusiness(next);
                  }}
                />
              </div>
            ) : null}

            <div className="flex justify-between pt-2">
              <Button
                type="button"
                variant="outline"
                disabled={step === 1}
                onClick={() => setStep((s) => s - 1)}
              >
                Back
              </Button>
              {step < 3 ? (
                <Button type="button" disabled={!canContinue} onClick={() => setStep((s) => s + 1)}>
                  Continue
                </Button>
              ) : step === 3 ? (
                <Button type="submit" disabled={!canContinue || loading}>
                  {loading ? "Building..." : "Build My Business Brain"}
                </Button>
              ) : (
                <div className="flex flex-wrap gap-2">
                  <Button type="button" variant="outline" onClick={() => finishOnboarding("/dashboard")}>
                    Skip for now
                  </Button>
                  <Button type="button" onClick={() => finishOnboarding("/opportunities")}>
                    Go to opportunities
                  </Button>
                </div>
              )}
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
