import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { studioClient } from '@/api/studioClient';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { UserPlus, Mail, Lock, Loader2 } from 'lucide-react';
import AuthLayout from '@/components/AuthLayout';

export default function Register(){
  const [email,setEmail]=useState(''),[password,setPassword]=useState(''),[confirmPassword,setConfirmPassword]=useState(''),[error,setError]=useState(''),[loading,setLoading]=useState(false);
  const submit=async(e)=>{e.preventDefault();setError('');if(password!==confirmPassword){setError('Passwords do not match');return;}setLoading(true);try{await studioClient.auth.register({email,password});window.location.href='/';}catch(err){setError(err.message||'Registration failed')}finally{setLoading(false)}};
  return <AuthLayout icon={UserPlus} title="Create your account" subtitle="Create a local SHiRE Dental account" footer={<>Already have an account? <Link to="/login" className="text-primary font-medium hover:underline">Log in</Link></>}>
    {error&&<div className="mb-4 p-3 rounded-lg bg-destructive/10 text-destructive text-sm">{error}</div>}
    <form onSubmit={submit} className="space-y-4">
      <div className="space-y-2"><Label htmlFor="email">Email</Label><div className="relative"><Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"/><Input id="email" type="email" value={email} onChange={e=>setEmail(e.target.value)} className="pl-10 h-12" required/></div></div>
      <div className="space-y-2"><Label htmlFor="password">Password</Label><div className="relative"><Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"/><Input id="password" type="password" value={password} onChange={e=>setPassword(e.target.value)} className="pl-10 h-12" required minLength={8}/></div></div>
      <div className="space-y-2"><Label htmlFor="confirm">Confirm password</Label><Input id="confirm" type="password" value={confirmPassword} onChange={e=>setConfirmPassword(e.target.value)} className="h-12" required minLength={8}/></div>
      <Button type="submit" className="w-full h-12" disabled={loading}>{loading?<><Loader2 className="w-4 h-4 mr-2 animate-spin"/>Creating account…</>:'Create account'}</Button>
    </form>
  </AuthLayout>;
}
