import { useState, type ComponentType, type ReactNode } from 'react';
import {
  Check,
  ChevronLeft,
  ChevronRight,
  KeyRound,
  LockKeyhole,
  Settings2,
  ShieldCheck,
  UserPlus,
  X,
} from 'lucide-react';
import { toast } from 'sonner';
import { api } from '@/api';
import { errMessage } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { BRAND } from '@/lib/brand';
import { BrandGlyph, BrandMark } from '@/components/brand/Brand';

function PromiseItem({
  icon: Icon,
  title,
  children,
}: {
  icon: ComponentType<{ className?: string }>;
  title: string;
  children: ReactNode;
}) {
  return (
    <div className="flex gap-3 rounded-xl border border-border/65 bg-card/55 p-3 shadow-sm shadow-black/5 backdrop-blur-sm">
      <span className="grid h-9 w-9 shrink-0 place-items-center rounded-lg border border-primary/20 bg-primary/10 text-primary">
        <Icon className="h-4 w-4" aria-hidden="true" />
      </span>
      <div className="min-w-0">
        <p className="text-sm font-semibold text-foreground">{title}</p>
        <p className="mt-0.5 text-xs leading-5 text-muted-foreground">{children}</p>
      </div>
    </div>
  );
}

export default function OnboardingWizard({ onComplete }: { onComplete: () => void }) {
  const [step, setStep] = useState(0);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    let validationError = '';
    if (password !== confirm) {
      validationError = 'Passwords do not match.';
    } else if (password.length < 8) {
      validationError = 'Password must be at least 8 characters.';
    }

    if (validationError) {
      setError(validationError);
      toast.error(validationError);
      return;
    }

    setLoading(true);
    try {
      await api.createUser({ username, password });
      toast.success('User created successfully.');
      onComplete();
    } catch (err) {
      const errorMessage = errMessage(err, 'Failed to create user.');
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-[calc(100vh-64px)] bg-[radial-gradient(circle_at_18%_4%,oklch(var(--primary)/0.13),transparent_28rem),radial-gradient(circle_at_86%_86%,oklch(var(--accent)/0.10),transparent_24rem)] px-4 py-10 sm:px-6 lg:px-8">
      <div className="mx-auto grid min-h-[calc(100vh-64px-5rem)] w-full max-w-5xl items-center gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(23rem,28rem)]">
        <section className="space-y-6">
          <div className="max-w-xl">
            <BrandMark className="h-auto w-[15rem] drop-shadow-[0_14px_36px_rgba(0,0,0,0.18)]" />
            <h1 className="mt-6 text-3xl font-semibold tracking-tight sm:text-4xl">
              Set up {BRAND.name} with a clean privacy line.
            </h1>
            <p className="mt-4 max-w-lg text-sm leading-6 text-muted-foreground sm:text-base sm:leading-7">
              The first admin keeps the app healthy. The first user owns the money data. Those roles
              stay separate from the start.
            </p>
          </div>

          <div className="grid max-w-xl gap-3 sm:grid-cols-2 lg:grid-cols-1">
            <PromiseItem icon={Settings2} title="Admin controls access">
              Create accounts, reset passwords, notification plumbing, and login mode settings.
            </PromiseItem>
            <PromiseItem icon={LockKeyhole} title="Financial data stays private">
              Admin tools do not expose bills, payments, spending history, or personal settings.
            </PromiseItem>
            <PromiseItem icon={ShieldCheck} title="Premium calm by default">
              A restrained setup flow that matches the tracker, settings, and security surfaces.
            </PromiseItem>
          </div>
        </section>

        <div className="w-full">
          <div className="mb-6 flex items-center justify-center gap-2">
            {[0, 1].map((i) => (
              <span
                key={i}
                className={`h-2 rounded-full transition-all ${i === step ? 'w-8 bg-primary' : 'w-2.5 bg-border'}`}
              />
            ))}
          </div>

          {step === 0 && (
            <Card className="overflow-hidden">
              <CardHeader>
                <div className="flex gap-3">
                  <BrandGlyph name="security" className="h-11 w-11 rounded-2xl" />
                  <div>
                    <CardTitle className="text-xl">Welcome, Administrator</CardTitle>
                    <p className="mt-1 text-sm text-muted-foreground">
                      Before creating your first user, review the admin boundary.
                    </p>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="space-y-2.5">
                  {[
                    { can: true, text: 'Create and manage user accounts' },
                    { can: true, text: 'Reset user passwords' },
                    { can: true, text: 'Configure email notifications' },
                    { can: true, text: 'Toggle single-user / multi-user mode' },
                    { can: false, text: 'Cannot view bills or financial data' },
                    { can: false, text: 'Cannot access user settings or history' },
                  ].map(({ can, text }) => (
                    <div key={text} className="flex items-center gap-3 text-sm">
                      <span
                        className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-full border ${can ? 'border-emerald-500/25 bg-emerald-500/15 text-emerald-500' : 'border-rose-500/25 bg-rose-500/15 text-rose-500'}`}
                      >
                        {can ? (
                          <Check className="h-3.5 w-3.5" aria-hidden="true" />
                        ) : (
                          <X className="h-3.5 w-3.5" aria-hidden="true" />
                        )}
                      </span>
                      <span className={can ? 'text-foreground' : 'text-muted-foreground'}>
                        {text}
                      </span>
                    </div>
                  ))}
                </div>
                <div className="pt-4">
                  <Button className="w-full" onClick={() => setStep(1)}>
                    Create the first user
                    <ChevronRight className="h-4 w-4" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          )}

          {step === 1 && (
            <Card className="overflow-hidden">
              <CardHeader>
                <div className="flex gap-3">
                  <BrandGlyph name="tracker" className="h-11 w-11 rounded-2xl" />
                  <div>
                    <CardTitle className="text-xl">Create first user</CardTitle>
                    <p className="mt-1 text-sm text-muted-foreground">
                      This account will own the tracker, bills, and personal settings.
                    </p>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <form onSubmit={handleCreate} className="space-y-4">
                  <div className="space-y-1.5">
                    <Label htmlFor="ob-username">Username</Label>
                    <Input
                      id="ob-username"
                      placeholder="username"
                      value={username}
                      onChange={(e) => setUsername(e.target.value)}
                      required
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label htmlFor="ob-password">Password</Label>
                    <Input
                      id="ob-password"
                      type="password"
                      placeholder="Password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      required
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label htmlFor="ob-confirm">Confirm password</Label>
                    <Input
                      id="ob-confirm"
                      type="password"
                      placeholder="Confirm password"
                      value={confirm}
                      onChange={(e) => setConfirm(e.target.value)}
                      required
                    />
                  </div>
                  {error && (
                    <div className="rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2 text-sm text-destructive">
                      {error}
                    </div>
                  )}
                  <div className="flex gap-2 pt-2">
                    <Button type="button" variant="outline" onClick={() => setStep(0)}>
                      <ChevronLeft className="h-4 w-4" />
                      Back
                    </Button>
                    <Button type="submit" className="flex-1" disabled={loading} aria-busy={loading}>
                      {loading ? (
                        'Creating…'
                      ) : (
                        <>
                          <UserPlus className="h-4 w-4" aria-hidden="true" />
                          Create User
                        </>
                      )}
                    </Button>
                  </div>
                  <div className="flex items-start gap-2 rounded-xl border border-border/70 bg-muted/35 p-3 text-xs leading-5 text-muted-foreground">
                    <KeyRound className="mt-0.5 h-4 w-4 shrink-0 text-primary" aria-hidden="true" />
                    <span>
                      Use a strong password now. The account can add two-factor authentication after
                      first sign-in.
                    </span>
                  </div>
                </form>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}
