"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { signIn } from "next-auth/react";
import {
  ScanLine,
  User,
  Building2,
  MapPin,
  Loader2,
  ArrowRight,
  Check,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

const STEPS = [
  { label: "Account", icon: User },
  { label: "Organization", icon: Building2 },
  { label: "Location", icon: MapPin },
];

export default function SetupPage() {
  const router = useRouter();
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [orgId, setOrgId] = useState("");

  const [account, setAccount] = useState({ displayName: "", email: "", password: "", confirmPassword: "" });
  const [org, setOrg] = useState({ name: "", type: "church", timezone: "America/Chicago" });
  const [location, setLocation] = useState({ name: "", address: "" });

  useEffect(() => {
    fetch("/api/setup")
      .then((r) => r.json())
      .then((data) => {
        if (data.isSetupComplete) {
          router.replace("/login");
          return;
        }
        setCurrentStep(data.setupStep || 0);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [router]);

  async function submitStep(step: number, data: Record<string, unknown>) {
    setSubmitting(true);
    setError("");

    try {
      const res = await fetch("/api/setup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ step, data }),
      });

      const result = await res.json();
      if (!res.ok) {
        setError(result.error || "Something went wrong");
        setSubmitting(false);
        return;
      }

      if (result.orgId) setOrgId(result.orgId);

      if (result.complete) {
        await signIn("credentials", {
          email: account.email,
          password: account.password,
          callbackUrl: "/",
        });
        return;
      }

      setCurrentStep(result.nextStep);
    } catch {
      setError("Something went wrong");
    } finally {
      setSubmitting(false);
    }
  }

  function handleAccountSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (account.password !== account.confirmPassword) {
      setError("Passwords do not match");
      return;
    }
    if (account.password.length < 8) {
      setError("Password must be at least 8 characters");
      return;
    }
    submitStep(1, account);
  }

  function handleOrgSubmit(e: React.FormEvent) {
    e.preventDefault();
    submitStep(2, org);
  }

  function handleLocationSubmit(e: React.FormEvent) {
    e.preventDefault();
    submitStep(3, { ...location, organizationId: orgId });
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="size-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="glass-card mx-auto w-full max-w-lg rounded-2xl p-8">
      <div className="mb-8 flex flex-col items-center">
        <div className="mb-4 flex size-14 items-center justify-center rounded-2xl gradient-banner shadow-lg">
          <ScanLine className="size-7 text-white" />
        </div>
        <h1 className="text-2xl font-bold tracking-tight">Set up Echo</h1>
        <p className="mt-1 text-sm text-muted-foreground">
          Configure your instance in a few steps
        </p>
      </div>

      <div className="mb-8 flex items-center justify-center gap-2">
        {STEPS.map((step, i) => {
          const done = currentStep > i;
          const active = currentStep === i;
          return (
            <div key={step.label} className="flex items-center gap-2">
              <div
                className={`flex size-8 items-center justify-center rounded-full text-xs font-bold transition-colors ${
                  done
                    ? "bg-emerald-500 text-white"
                    : active
                      ? "bg-primary text-primary-foreground"
                      : "bg-muted text-muted-foreground"
                }`}
              >
                {done ? <Check className="size-4" /> : i + 1}
              </div>
              <span
                className={`hidden text-xs font-medium sm:inline ${
                  active ? "text-foreground" : "text-muted-foreground"
                }`}
              >
                {step.label}
              </span>
              {i < STEPS.length - 1 && (
                <ArrowRight className="size-3 text-muted-foreground/50" />
              )}
            </div>
          );
        })}
      </div>

      {error && (
        <div className="mb-4 rounded-lg bg-destructive/10 p-3 text-center text-sm text-destructive">
          {error}
        </div>
      )}

      {currentStep === 0 && (
        <form onSubmit={handleAccountSubmit} className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Create the owner account for this instance.
          </p>
          <div className="space-y-2">
            <Label htmlFor="displayName">Full Name</Label>
            <Input
              id="displayName"
              value={account.displayName}
              onChange={(e) => setAccount((p) => ({ ...p, displayName: e.target.value }))}
              required
              placeholder="John Smith"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              value={account.email}
              onChange={(e) => setAccount((p) => ({ ...p, email: e.target.value }))}
              required
              placeholder="you@church.org"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="password">Password</Label>
            <Input
              id="password"
              type="password"
              value={account.password}
              onChange={(e) => setAccount((p) => ({ ...p, password: e.target.value }))}
              required
              minLength={8}
              placeholder="Min 8 characters"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="confirmPassword">Confirm Password</Label>
            <Input
              id="confirmPassword"
              type="password"
              value={account.confirmPassword}
              onChange={(e) => setAccount((p) => ({ ...p, confirmPassword: e.target.value }))}
              required
              minLength={8}
              placeholder="Confirm password"
            />
          </div>
          <Button type="submit" className="w-full rounded-xl" disabled={submitting}>
            {submitting && <Loader2 className="mr-2 size-4 animate-spin" />}
            Create Account
          </Button>
        </form>
      )}

      {currentStep === 1 && (
        <form onSubmit={handleOrgSubmit} className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Set up your organization.
          </p>
          <div className="space-y-2">
            <Label htmlFor="orgName">Organization Name</Label>
            <Input
              id="orgName"
              value={org.name}
              onChange={(e) => setOrg((p) => ({ ...p, name: e.target.value }))}
              required
              placeholder="Grace Community Church"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="orgType">Type</Label>
            <Input
              id="orgType"
              value={org.type}
              onChange={(e) => setOrg((p) => ({ ...p, type: e.target.value }))}
              placeholder="church"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="timezone">Timezone</Label>
            <Input
              id="timezone"
              value={org.timezone}
              onChange={(e) => setOrg((p) => ({ ...p, timezone: e.target.value }))}
              placeholder="America/Chicago"
            />
          </div>
          <Button type="submit" className="w-full rounded-xl" disabled={submitting}>
            {submitting && <Loader2 className="mr-2 size-4 animate-spin" />}
            Create Organization
          </Button>
        </form>
      )}

      {currentStep === 2 && (
        <form onSubmit={handleLocationSubmit} className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Add your first location or campus.
          </p>
          <div className="space-y-2">
            <Label htmlFor="locName">Location Name</Label>
            <Input
              id="locName"
              value={location.name}
              onChange={(e) => setLocation((p) => ({ ...p, name: e.target.value }))}
              required
              placeholder="Main Campus"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="locAddress">Address (optional)</Label>
            <Input
              id="locAddress"
              value={location.address}
              onChange={(e) => setLocation((p) => ({ ...p, address: e.target.value }))}
              placeholder="123 Church St, City, ST 12345"
            />
          </div>
          <Button type="submit" className="w-full rounded-xl" disabled={submitting}>
            {submitting && <Loader2 className="mr-2 size-4 animate-spin" />}
            Complete Setup
          </Button>
        </form>
      )}
    </div>
  );
}
