'use client';

/**
 * Setup Page
 * Initial system setup (first time only)
 */

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { authAPI } from '@/lib/api/auth';
import { Button, Input, Card, CardHeader, CardTitle, CardContent } from '@/components/ui';
import toast from 'react-hot-toast';

// Validation schema
const setupSchema = z.object({
  username: z.string().min(3, 'Username must be at least 3 characters'),
  email: z.string().email('Invalid email address'),
  password: z.string().min(6, 'Password must be at least 6 characters'),
  full_name: z.string().min(1, 'Full name is required'),
});

export default function SetupPage() {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(setupSchema),
  });

  const onSubmit = async (data) => {
    setIsLoading(true);
    try {
      const response = await authAPI.setup(data);
      
      if (response.success) {
        toast.success('System setup completed! Please login.');
        router.push('/login');
      } else {
        toast.error(response.message || 'Setup failed. Please try again.');
      }
    } catch (error) {
      toast.error(error.message || 'An error occurred during setup.');
      console.error('Setup error:', error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        {/* Header */}
        <div className="text-center">
          <h1 className="text-4xl font-bold text-gray-900">XYZ POS</h1>
          <p className="mt-2 text-gray-600">Initial System Setup</p>
        </div>

        {/* Setup Card */}
        <Card>
          <CardHeader>
            <CardTitle>Create Admin Account</CardTitle>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
              <Input
                label="Full Name"
                type="text"
                placeholder="Enter your full name"
                {...register('full_name')}
                error={errors.full_name?.message}
                disabled={isLoading}
                autoFocus
              />

              <Input
                label="Username"
                type="text"
                placeholder="Choose a username"
                {...register('username')}
                error={errors.username?.message}
                disabled={isLoading}
              />

              <Input
                label="Email"
                type="email"
                placeholder="Enter your email"
                {...register('email')}
                error={errors.email?.message}
                disabled={isLoading}
              />

              <Input
                label="Password"
                type="password"
                placeholder="Choose a password (min 6 characters)"
                {...register('password')}
                error={errors.password?.message}
                disabled={isLoading}
              />

              <Button
                type="submit"
                variant="primary"
                className="w-full"
                disabled={isLoading}
                loading={isLoading}
              >
                Complete Setup
              </Button>
            </form>
          </CardContent>
        </Card>

        {/* Footer */}
        <p className="text-center text-sm text-gray-600">
          This setup is only needed once. After setup, you can login normally.
        </p>
      </div>
    </div>
  );
}

