"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { FormEvent, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { USER_ROLE_TITLES } from "@/lib/constants";
import { clearBusiness, getActiveDemoId, getBusiness, loadDemoProfile, saveBusiness } from "@/lib/data-store";
import { DEMO_PROFILES } from "@/lib/demo-profiles";
import { inferUserRoleTitle } from "@/lib/user-workplace-role";
import { SamGovIntegrationCard } from "@/components/settings/sam-gov-integration-card";
import { WordPressIntegrationCard } from "@/components/settings/wordpress-integration-card";
import type { Business } from "@/lib/types";

export default function SettingsPage() {
  const router = useRouter();
  const [business, setBusiness] = useState<Business | null>(null);
  const [activeDemoId, setActiveDemoId] = useState<string | null>(null);
  const [saved, setSaved] = useState(false);
  const [switching, setSwitching] = useState<string | null>(null);

  useEffect(() => {
    getBusiness().then(setBusiness);
    setActiveDemoId(getActiveDemoId());
  }, []);

  const onSave = async (e: FormEvent) => {
    e.preventDefault();
    if (!business) return;
    await saveBusiness({ ...business, updatedAt: new Date().toISOString() });
    setSaved(true);
    setTimeout(() => setSaved(false), 1500);
  };

  const switchDemo = async (id: string) => {
    setSwitching(id);
    await loadDemoProfile(id);
    setActiveDemoId(id);
    const updated = await getBusiness();
    setBusiness(updated);
    setSwitching(null);
    router.push("/dashboard");
  };

  const resetData = async () => {
    await clearBusiness();
    setBusiness(null);
    setActiveDemoId(null);
    router.push("/demo");
  };

  if (!business) return null;

  return (
    <div className="space-y-4 py-4">
      <Card>
        <CardHeader>
          <CardTitle>Switch demo business</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid gap-2 sm:grid-cols-2">
            {DEMO_PROFILES.map((demo) => (
              <button
                key={demo.id}
                type="button"
                onClick={() => switchDemo(demo.id)}
                disabled={switching === demo.id}
                className={`rounded-xl border p-3 text-left transition hover:border-sky-500/40 hover:bg-sky-500/5 ${
                  activeDemoId === demo.id ? "border-sky-500/50 bg-sky-500/10" : "border-slate-800"
                }`}
              >
                <p className="font-medium text-slate-100">{demo.name}</p>
                <p className="text-xs text-slate-400">{demo.industry} · {demo.location}</p>
                {activeDemoId === demo.id ? (
                  <p className="mt-1 text-xs text-sky-400">Active demo</p>
                ) : null}
              </button>
            ))}
          </div>
          <div className="mt-4 flex flex-wrap gap-2">
            <Link href="/demo">
              <Button variant="outline" size="sm">Browse all demos</Button>
            </Link>
            <Button variant="ghost" size="sm" onClick={resetData}>
              Clear data & pick new demo
            </Button>
          </div>
        </CardContent>
      </Card>

      <Card id="your-role" className="scroll-mt-6 border-amber-500/20">
        <CardHeader>
          <CardTitle>Your role & AI Leader</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <p className="text-sm text-slate-400">
            Set your title inside the company — usually owner or boss. Turn on AI Leader when you want BrandLxft to drive priorities, assign role agents, and hold you accountable.
          </p>
          <Select
            value={business.userRole?.title ?? inferUserRoleTitle(business)}
            onChange={(e) =>
              setBusiness((prev) =>
                prev
                  ? {
                      ...prev,
                      userRole: {
                        title: e.target.value,
                        aiLeaderEnabled: prev.userRole?.aiLeaderEnabled ?? false,
                      },
                    }
                  : prev,
              )
            }
          >
            {USER_ROLE_TITLES.map((title) => (
              <option key={title} value={title}>
                {title}
              </option>
            ))}
          </Select>
          <label className="flex cursor-pointer items-start gap-3 rounded-xl border border-slate-800 p-4 transition hover:border-amber-500/30">
            <input
              type="checkbox"
              className="mt-1"
              checked={business.userRole?.aiLeaderEnabled ?? false}
              onChange={(e) =>
                setBusiness((prev) =>
                  prev
                    ? {
                        ...prev,
                        userRole: {
                          title: prev.userRole?.title ?? inferUserRoleTitle(prev),
                          aiLeaderEnabled: e.target.checked,
                        },
                      }
                    : prev,
                )
              }
            />
            <span>
              <span className="block font-medium text-slate-100">Enable AI Leader</span>
              <span className="text-sm text-slate-400">
                BrandLxft acts as your boss — locks today&apos;s priority, delegates to role agents, and sends accountability check-ins with receipts.
              </span>
            </span>
          </label>
          <Button
            type="button"
            onClick={async () => {
              if (!business) return;
              await saveBusiness({ ...business, updatedAt: new Date().toISOString() });
              setSaved(true);
              setTimeout(() => setSaved(false), 1500);
            }}
          >
            Save role settings
          </Button>
        </CardContent>
      </Card>

      <div id="integrations" className="scroll-mt-6 space-y-4">
        <div>
          <h2 className="text-lg font-semibold text-slate-100">Integrations</h2>
          <p className="text-sm text-slate-400">
            Connect SAM.gov for live federal bids and your website host so Role Agents can push updates (with your approval).
          </p>
        </div>
        <WordPressIntegrationCard business={business} onUpdate={setBusiness} />
        <SamGovIntegrationCard business={business} onUpdate={setBusiness} />
      </div>

      <Card className="py-4">
      <CardHeader>
        <CardTitle>Settings</CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={onSave} className="space-y-3">
          <Input
            placeholder="Business name"
            value={business.input.businessName}
            onChange={(e) =>
              setBusiness((prev) =>
                prev ? { ...prev, input: { ...prev.input, businessName: e.target.value } } : prev
              )
            }
          />
          <Input
            placeholder="Website URL"
            value={business.input.websiteUrl}
            onChange={(e) =>
              setBusiness((prev) =>
                prev ? { ...prev, input: { ...prev.input, websiteUrl: e.target.value } } : prev
              )
            }
          />
          <Input
            placeholder="Location"
            value={business.input.location}
            onChange={(e) =>
              setBusiness((prev) =>
                prev ? { ...prev, input: { ...prev.input, location: e.target.value } } : prev
              )
            }
          />
          <Textarea
            placeholder="Target customer"
            value={business.input.targetCustomer}
            onChange={(e) =>
              setBusiness((prev) =>
                prev ? { ...prev, input: { ...prev.input, targetCustomer: e.target.value } } : prev
              )
            }
          />
          <Textarea
            placeholder="Revenue goal"
            value={business.input.revenueGoal}
            onChange={(e) =>
              setBusiness((prev) =>
                prev ? { ...prev, input: { ...prev.input, revenueGoal: e.target.value } } : prev
              )
            }
          />
          <Button type="submit">Save settings</Button>
          {saved ? <p className="text-sm text-emerald-400">Saved.</p> : null}
        </form>
      </CardContent>
    </Card>
    </div>
  );
}
