import {StrictMode,useEffect,useState} from 'react'
import {createRoot} from 'react-dom/client'
import {BrowserRouter,NavLink,Navigate,Route,Routes} from 'react-router-dom'
import {useForm} from 'react-hook-form'
import {QueryClient,QueryClientProvider,useQuery} from '@tanstack/react-query'
import {Bell,Building2,CalendarDays,ClipboardCheck,Clock3,FileText,House,LogOut,Settings2,UserRound,UsersRound} from 'lucide-react'
import type {Session} from '@supabase/supabase-js'
import {configured,credentials,db,errorText,fullName,lang,rpc,tr,useRows,type Employee,type Property} from './lib'
import {ActionForm,DataState,Field,str} from './ui'
import {AttendancePage,ClockHome,Notifications,RequestsPage} from './work'
import {Directory,Profile,Settings} from './admin'
import {Roster} from './roster'
import './style.css'

const query=new QueryClient({defaultOptions:{queries:{retry:false,staleTime:10000}}})
const recoveryUrl=location.hash.includes('type=recovery')||location.pathname==='/recover'
function Language(){
 return <a href={location.pathname+'?'+new URLSearchParams({...Object.fromEntries(new URLSearchParams(location.search)),lang:lang==='th'?'en':'th'})} className="language" aria-label={tr('เปลี่ยนภาษาเป็นอังกฤษ','Switch to Thai')}>{lang==='th'?'EN':'ไทย'}</a>
}
function Brand(){return <div className="brand"><span><Building2 size={21}/></span><strong>Hotel HR Mini</strong></div>}
function Login(){
 const {register,handleSubmit,formState}=useForm<{email:string;password:string}>()
 const [notice,setNotice]=useState(''),[reset,setReset]=useState(false)
 async function login(input:{email:string;password:string}){
  setNotice('')
  const checked=credentials.safeParse(input)
  if(!checked.success){setNotice(tr('กรุณาตรวจอีเมลและรหัสผ่าน','Check your email and password'));return}
  const {error}=await db.auth.signInWithPassword(checked.data)
  if(error)setNotice(tr('เข้าสู่ระบบไม่ได้ กรุณาตรวจข้อมูลหรือลองใหม่','Sign-in failed. Check your credentials or try again.'))
 }
 return <main className="auth-shell"><div className="auth-card"><div className="split"><Brand/><Language/></div>
 <h1>{reset?tr('ตั้งรหัสผ่านใหม่','Reset password'):tr('เข้าสู่ระบบ','Sign in')}</h1>
 {!configured?<p className="error">{tr('ระบบนี้ยังไม่ได้ตั้งค่าการเชื่อมต่อ Supabase','Supabase has not been configured.')}</p>:reset?
 <ActionForm label={tr('ขอลิงก์ตั้งรหัสผ่าน','Request recovery link')} action={async d=>{
  const redirectTo=new URL('/recover',location.origin).href
  const {error}=await db.auth.resetPasswordForEmail(str(d,'email'),{redirectTo})
  if(error)throw error
 }}><Field label={tr('อีเมล','Email')}><input name="email" type="email" autoComplete="email" required/></Field><p className="muted">{tr('หากไม่ได้รับอีเมล กรุณาติดต่อผู้ดูแลระบบ','Contact your administrator if the email does not arrive.')}</p></ActionForm>:
 <form className="form" onSubmit={handleSubmit(login)}><fieldset disabled={formState.isSubmitting}><Field label={tr('อีเมล','Email')}><input {...register('email')} type="email" autoComplete="username" required/></Field>
 <Field label={tr('รหัสผ่าน','Password')}><input {...register('password')} type="password" autoComplete="current-password" required/></Field></fieldset>
 <button className="primary" disabled={formState.isSubmitting}>{tr('เข้าสู่ระบบ','Sign in')}</button>
 {notice&&<p role="alert" className="error">{notice}</p>}</form>}
 {configured&&<button className="link-button" onClick={()=>setReset(!reset)}>{reset?tr('กลับสู่หน้าเข้าสู่ระบบ','Back to login'):tr('ลืมรหัสผ่าน','Forgot password?')}</button>}
 </div></main>
}
function Verification({complete}:{complete:()=>void}){
 const [factor,setFactor]=useState(''),[secret,setSecret]=useState(''),[error,setError]=useState(''),[loading,setLoading]=useState(true)
 useEffect(()=>{let alive=true;void db.auth.mfa.listFactors().then(({data,error})=>{
  if(!alive)return
  if(error)setError(errorText(error));else if(data.totp[0])setFactor(data.totp[0].id)
  setLoading(false)
 });return()=>{alive=false}},[])
 async function enroll(){
  setLoading(true);setError('')
  try{
   const existing=await db.auth.mfa.listFactors()
   if(existing.error)throw existing.error
   for(const entry of existing.data.all.filter(f=>f.status==='unverified'&&f.factor_type==='totp')){
    const {error}=await db.auth.mfa.unenroll({factorId:entry.id});if(error)throw error
   }
   const {data,error}=await db.auth.mfa.enroll({factorType:'totp',issuer:'Hotel HR Mini'});if(error)throw error
   setSecret(data.totp.secret);setFactor(data.id)
  }catch(e){setError(errorText(e))}finally{setLoading(false)}
 }
 return <main className="auth-shell"><div className="auth-card"><Brand/><h1>{tr('ยืนยันตัวตนสองขั้นตอน','Two-factor verification')}</h1>
 {loading?<p role="status">{tr('กำลังโหลด…','Loading…')}</p>:factor?
 <ActionForm label={tr('ยืนยันรหัส','Verify code')} action={async d=>{
  const {error}=await db.auth.mfa.challengeAndVerify({factorId:factor,code:str(d,'code')});if(error)throw error
 }} after={complete}>{secret&&<><p>{tr('เพิ่มบัญชีในแอป Authenticator ด้วยรหัสตั้งค่านี้','Enter this setup key in your authenticator.')}</p><code className="secret">{secret}</code></>}
 <Field label={tr('รหัส 6 หลัก','Six-digit code')}><input name="code" inputMode="numeric" autoComplete="one-time-code" pattern="[0-9]{6}" required/></Field></ActionForm>:
 <button className="primary" onClick={()=>void enroll()}>{tr('ตั้งค่าแอป Authenticator','Set up authenticator')}</button>}
 {error&&<p className="error">{error}</p>}<button className="link-button" onClick={()=>void db.auth.signOut()}>{tr('ออกจากระบบ','Sign out')}</button></div></main>
}
function Recovery(){
 return <main className="auth-shell"><div className="auth-card"><Brand/><h1>{tr('ตั้งรหัสผ่านใหม่','Set a new password')}</h1>
 <ActionForm label={tr('บันทึกรหัสผ่าน','Save password')} action={async d=>{
  const {error}=await db.auth.updateUser({password:str(d,'password')});if(error)throw error
  const result=await db.auth.signOut();if(result.error)throw result.error
  location.replace('/')
 }}><Field label={tr('รหัสผ่านใหม่ (อย่างน้อย 12 ตัว)','New password (at least 12 characters)')}><input name="password" type="password" autoComplete="new-password" minLength={12} maxLength={128} required/></Field></ActionForm>
 </div></main>
}
function SignedIn(){
 const me=useQuery({queryKey:['my_profile'],queryFn:()=>rpc<Employee|null>('my_profile')})
 const verification=useQuery({queryKey:['aal'],queryFn:async()=>{const {data,error}=await db.auth.mfa.getAuthenticatorAssuranceLevel();if(error)throw error;return data}})
 return <DataState queries={[me,verification]}>{!me.data?.id?<main className="auth-shell"><div className="auth-card"><Brand/><p role="alert">{tr('บัญชียังไม่ได้ผูกกับพนักงานหรือถูกปิดใช้งาน','This account is unlinked or inactive.')}</p><button onClick={()=>void db.auth.signOut()}>{tr('ออกจากระบบ','Sign out')}</button></div></main>:me.data.role!=='employee'&&verification.data?.currentLevel!=='aal2'?<Verification complete={()=>void query.invalidateQueries()}/>:<Shell me={me.data}/>}</DataState>
}
function Shell({me}:{me:Employee}){
 const props=useRows<Property>('properties',q=>q.order('code').limit(100))
 const manager=me.role!=='employee',owner=me.role==='owner'
 const [offline,setOffline]=useState(!navigator.onLine)
 useEffect(()=>{const update=()=>setOffline(!navigator.onLine);addEventListener('online',update);addEventListener('offline',update);return()=>{removeEventListener('online',update);removeEventListener('offline',update)}},[])
 const first=manager?'/overview':'/'
 const links=[{path:first,name:manager?tr('ภาพรวม','Overview'):tr('ลงเวลา','Clock'),icon:manager?House:Clock3},
 ...(me.role==='manager'?[{path:'/',name:tr('ลงเวลา','Clock'),icon:Clock3},{path:'/my-schedule',name:tr('กะของฉัน','My shifts'),icon:CalendarDays}]:[]),
 {path:'/schedule',name:tr('ตารางงาน','Schedule'),icon:CalendarDays},
 ...(manager?[{path:'/approvals',name:tr('อนุมัติ','Approvals'),icon:ClipboardCheck},{path:'/employees',name:tr('พนักงาน','Employees'),icon:UsersRound}]:[]),
 ...(owner?[]:[{path:'/requests',name:tr('คำขอ','Requests'),icon:ClipboardCheck}]),
 {path:'/attendance',name:tr('ประวัติเวลา','Attendance'),icon:FileText},
 {path:'/notifications',name:tr('แจ้งเตือน','Notices'),icon:Bell},
 {path:'/profile',name:tr('โปรไฟล์','Profile'),icon:UserRound},
 ...(owner?[{path:'/settings',name:tr('ตั้งค่า','Settings'),icon:Settings2}]:[])]
 const properties=props.data??[]
 const work={me,properties}
 return <div className="layout">
 <aside><Brand/><nav aria-label={tr('เมนูหลัก','Main menu')}>{links.map(({path,name,icon:Icon})=><NavLink to={path+(lang==='en'?'?lang=en':'')} end={path==='/'} key={path}><Icon size={20}/><span>{name}</span></NavLink>)}</nav></aside>
 <div className="workspace"><header><div className="mobile-brand"><Brand/></div><div className="account"><span>{fullName(me)}</span><Language/><button aria-label={tr('ออกจากระบบ','Sign out')} title={tr('ออกจากระบบ','Sign out')} onClick={()=>void db.auth.signOut()}><LogOut size={18}/></button></div></header>
 <main className="content">
 {offline&&<p className="error" role="alert">{tr('ออฟไลน์ · ระบบลงเวลาใช้การเชื่อมต่ออินเทอร์เน็ต','Offline · Attendance requires an internet connection')}</p>}
 <DataState queries={[props]}><Routes>
 <Route path="/" element={owner?<Navigate to={'/overview'+(lang==='en'?'?lang=en':'')} replace/>:<ClockHome {...work}/>}/>
 <Route path="/my-schedule" element={me.role==='manager'?<Roster {...work} manage={false} ownOnly/>:<Navigate to={first} replace/>}/>
 <Route path="/schedule" element={<Roster {...work} manage={manager}/>}/>
 <Route path="/attendance" element={<AttendancePage {...work} manager={manager}/>}/>
 <Route path="/requests" element={!owner?<RequestsPage {...work}/>:<Navigate to={first} replace/>}/>
 <Route path="/notifications" element={<Notifications/>}/>
 <Route path="/profile" element={<Profile {...work}/>}/>
 <Route path="/overview" element={manager?<AttendancePage key="overview" {...work} manager dashboard/>:<Navigate to={first} replace/>}/>
 <Route path="/approvals" element={manager?<RequestsPage key="approvals" {...work} approvals/>:<Navigate to={first} replace/>}/>
 <Route path="/employees" element={manager?<Directory properties={properties} owner={owner}/>:<Navigate to={first} replace/>}/>
 <Route path="/settings" element={owner?<Settings properties={properties}/>:<Navigate to={first} replace/>}/>
 <Route path="*" element={<Navigate to={first} replace/>}/>
 </Routes></DataState></main></div></div>
}
function App(){
 const [session,setSession]=useState<Session|null|undefined>(undefined),[recovery,setRecovery]=useState(recoveryUrl),[authIssue,setAuthIssue]=useState('')
 useEffect(()=>{
  if(!configured){setSession(null);return}
  let member:string|undefined
  const {data:{subscription}}=db.auth.onAuthStateChange((event,next)=>{
   if(member!==next?.user.id){query.clear();member=next?.user.id}
   setSession(next)
   if(event==='PASSWORD_RECOVERY')setRecovery(true)
   if(event==='SIGNED_OUT')setRecovery(false)
  })
  void db.auth.getSession().then(({error})=>{if(error){setAuthIssue(errorText(error));setSession(null)}})
  return ()=>subscription.unsubscribe()
 },[])
 if(session===undefined)return <div role="status" className="auth-shell">{tr('กำลังโหลด…','Loading…')}</div>
 if(session&&recovery)return <Recovery/>
 return <>{authIssue&&<p role="alert" className="error">{authIssue}</p>}{session?<SignedIn key={session.user.id}/>:<Login/>}</>
}
createRoot(document.getElementById('root')!).render(<StrictMode><QueryClientProvider client={query}><BrowserRouter><App/></BrowserRouter></QueryClientProvider></StrictMode>)
if(import.meta.env.PROD && 'serviceWorker' in navigator)void navigator.serviceWorker.register('/sw.js').catch(console.error)
