import React, { useEffect, useMemo, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { createClient } from '@supabase/supabase-js';
import { Bus, ClipboardList, Database, Upload, Search, Home, Camera, FileText, ExternalLink, Trash2, Download, RefreshCw } from 'lucide-react';
import fleetVehicles from './data/fleetVehicles.json';
import './styles.css';

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
const supabase = supabaseUrl && supabaseKey ? createClient(supabaseUrl, supabaseKey) : null;
const STORAGE_BUCKET = 'bus-log-uploads';

const emptyLog = {
  date: new Date().toISOString().slice(0, 10),
  time: new Date().toTimeString().slice(0, 5),
  shiftNumber: '',
  shiftType: 'Run printed shift',
  fleetNumber: '',
  registration: '',
  vehicleDescription: '',
  vehicleLocation: '',
  regoStatus: 'Not checked',
  gearNoise: '',
  power: '',
  bodyRattles: '',
  aircon: '',
  damageNotes: '',
  comments: '',
  photoName: '',
  photoUrl: '',
  runPrintName: '',
  runPrintUrl: '',
  createdAt: ''
};

function normaliseFleet(value) {
  return String(value || '').replace(/[^0-9A-Za-z]/g, '').toUpperCase();
}
function fileToDataUrl(file) {
  return new Promise((resolve, reject) => {
    if (!file) return resolve('');
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}
async function uploadFile(file, prefix) {
  if (!file) return { name: '', url: '' };
  if (!supabase) return { name: file.name, url: await fileToDataUrl(file) };
  const safeName = file.name.replace(/[^a-zA-Z0-9._-]/g, '_');
  const path = `${prefix}/${Date.now()}-${crypto.randomUUID()}-${safeName}`;
  const { error } = await supabase.storage.from(STORAGE_BUCKET).upload(path, file, { upsert: false });
  if (error) throw error;
  const { data } = supabase.storage.from(STORAGE_BUCKET).getPublicUrl(path);
  return { name: file.name, url: data.publicUrl };
}
async function loadLogs() {
  if (supabase) {
    const { data, error } = await supabase.from('bus_logs').select('*').order('created_at', { ascending: false });
    if (error) throw error;
    return data.map(row => ({
      id: row.id,
      date: row.drive_date,
      time: row.drive_time?.slice(0, 5) || '',
      shiftNumber: row.shift_number || '',
      shiftType: row.shift_type || '',
      fleetNumber: row.fleet_number || '',
      registration: row.registration || '',
      vehicleDescription: row.vehicle_description || '',
      vehicleLocation: row.vehicle_location || '',
      regoStatus: row.rego_status || 'Not checked',
      gearNoise: row.gear_noise || '',
      power: row.power || '',
      bodyRattles: row.body_rattles || '',
      aircon: row.aircon || '',
      damageNotes: row.damage_notes || '',
      comments: row.comments || '',
      photoName: row.photo_name || '',
      photoUrl: row.photo_url || '',
      runPrintName: row.run_print_name || '',
      runPrintUrl: row.run_print_url || '',
      createdAt: row.created_at || ''
    }));
  }
  return JSON.parse(localStorage.getItem('busLogs') || '[]');
}
async function saveLog(log) {
  if (supabase) {
    const { error } = await supabase.from('bus_logs').insert({
      drive_date: log.date,
      drive_time: log.time,
      shift_number: log.shiftNumber,
      shift_type: log.shiftType,
      fleet_number: log.fleetNumber,
      registration: log.registration,
      vehicle_description: log.vehicleDescription,
      vehicle_location: log.vehicleLocation,
      rego_status: log.regoStatus,
      gear_noise: log.gearNoise,
      power: log.power,
      body_rattles: log.bodyRattles,
      aircon: log.aircon,
      damage_notes: log.damageNotes,
      comments: log.comments,
      photo_name: log.photoName,
      photo_url: log.photoUrl,
      run_print_name: log.runPrintName,
      run_print_url: log.runPrintUrl
    });
    if (error) throw error;
    return;
  }
  const logs = JSON.parse(localStorage.getItem('busLogs') || '[]');
  logs.unshift({ ...log, id: crypto.randomUUID(), createdAt: new Date().toISOString() });
  localStorage.setItem('busLogs', JSON.stringify(logs));
}
async function deleteLog(id) {
  if (supabase) {
    const { error } = await supabase.from('bus_logs').delete().eq('id', id);
    if (error) throw error;
    return;
  }
  const logs = JSON.parse(localStorage.getItem('busLogs') || '[]').filter(l => l.id !== id);
  localStorage.setItem('busLogs', JSON.stringify(logs));
}

function RatingGroup({ label, value, onChange, options }) {
  return <section className="ratingGroup"><h3>{label}</h3><div className="pillRow">{options.map(opt => <label key={opt} className={value === opt ? 'pill selected' : 'pill'}><input type="radio" name={label} value={opt} checked={value === opt} onChange={() => onChange(opt)} />{opt}</label>)}</div></section>;
}

function LogBus({ fleetIndex, onSaved }) {
  const [form, setForm] = useState(emptyLog);
  const [photo, setPhoto] = useState(null);
  const [runPrint, setRunPrint] = useState(null);
  const [message, setMessage] = useState('');
  const [saving, setSaving] = useState(false);
  const set = (key, value) => setForm(prev => ({ ...prev, [key]: value }));
  const handleFleet = value => {
    const key = normaliseFleet(value);
    const vehicle = fleetIndex.get(key);
    setForm(prev => ({
      ...prev,
      fleetNumber: value,
      registration: vehicle?.registration || '',
      vehicleDescription: vehicle?.description || '',
      vehicleLocation: vehicle?.location || '',
      regoStatus: vehicle ? 'Use QLD Rego Check' : 'Vehicle not found'
    }));
  };
  const qldRegoUrl = 'https://www.service.transport.qld.gov.au/checkrego/application/VehicleSearch.xhtml';
  const submit = async e => {
    e.preventDefault();
    setSaving(true); setMessage('');
    try {
      const uploadedPhoto = await uploadFile(photo, 'photos');
      const uploadedRunPrint = form.shiftType === 'Run printed shift' ? await uploadFile(runPrint, 'run-prints') : { name: '', url: '' };
      await saveLog({ ...form, photoName: uploadedPhoto.name, photoUrl: uploadedPhoto.url, runPrintName: uploadedRunPrint.name, runPrintUrl: uploadedRunPrint.url });
      setForm({ ...emptyLog, date: new Date().toISOString().slice(0, 10), time: new Date().toTimeString().slice(0, 5) });
      setPhoto(null); setRunPrint(null); setMessage('Saved.'); onSaved?.();
    } catch (err) { setMessage(err.message || 'Could not save log.'); }
    finally { setSaving(false); }
  };
  return <main className="panel wide"><h2>Log a bus</h2><p className="hint">Designed for quick phone use at sign-on or sign-off.</p><form onSubmit={submit} className="formGrid">
    <label>Date<input type="date" value={form.date} onChange={e=>set('date',e.target.value)} required /></label>
    <label>Time<input type="time" value={form.time} onChange={e=>set('time',e.target.value)} required /></label>
    <label>Shift number<input value={form.shiftNumber} onChange={e=>set('shiftNumber',e.target.value)} placeholder="e.g. 412" /></label>
    <label>Shift type<select value={form.shiftType} onChange={e=>set('shiftType',e.target.value)}><option>Run printed shift</option><option>Charter</option></select></label>
    <label>Fleet number<input value={form.fleetNumber} onChange={e=>handleFleet(e.target.value)} placeholder="e.g. 1001" inputMode="numeric" required /></label>
    <label>Registration<input value={form.registration} onChange={e=>set('registration',e.target.value.toUpperCase())} placeholder="Auto-filled" /></label>
    <label className="span2">Vehicle details<input value={[form.vehicleDescription, form.vehicleLocation].filter(Boolean).join(' • ')} readOnly /></label>
    <div className="regoBox span2"><div><b>QLD rego status:</b> {form.regoStatus}</div>{form.registration && <a className="button secondary" href={qldRegoUrl} target="_blank" rel="noreferrer"><ExternalLink size={16}/> Open QLD Rego Check</a>}<small>Automatic QLD Rego Check lookup is not included because there is no public official API. Use the button to verify manually.</small></div>
    <div className="span2 ratings"><RatingGroup label="Gear noise" value={form.gearNoise} onChange={v=>set('gearNoise',v)} options={['Quiet','Noticeable','Loud']} /><RatingGroup label="Power" value={form.power} onChange={v=>set('power',v)} options={['Slow','Acceptable','Quick']} /><RatingGroup label="Body rattles" value={form.bodyRattles} onChange={v=>set('bodyRattles',v)} options={['Extreme','Reasonable','Loud']} /><RatingGroup label="Aircon" value={form.aircon} onChange={v=>set('aircon',v)} options={['Good','Bad']} /></div>
    <label className="span2">Damage/defect photo<input type="file" accept="image/*" capture="environment" onChange={e=>setPhoto(e.target.files?.[0] || null)} /></label>
    <label className="span2">Damage/defect notes<textarea value={form.damageNotes} onChange={e=>set('damageNotes',e.target.value)} placeholder="Damage location, defect details, when noticed..." /></label>
    <label className="span2">Comments<textarea value={form.comments} onChange={e=>set('comments',e.target.value)} placeholder="Anything else worth remembering about this bus or shift..." /></label>
    {form.shiftType === 'Run printed shift' && <label className="span2">Run print PDF<input type="file" accept="application/pdf" onChange={e=>setRunPrint(e.target.files?.[0] || null)} /></label>}
    <button className="button primary span2" disabled={saving}>{saving ? 'Saving...' : 'Save bus log'}</button>{message && <p className="message span2">{message}</p>}
  </form></main>;
}
function History({ logs, onRefresh, onDelete }) {
  const [query, setQuery] = useState('');
  const filtered = logs.filter(l => JSON.stringify(l).toLowerCase().includes(query.toLowerCase()));
  const exportCsv = () => {
    const headers = ['date','time','shiftNumber','shiftType','fleetNumber','registration','regoStatus','gearNoise','power','bodyRattles','aircon','damageNotes','comments','photoUrl','runPrintUrl'];
    const csv = [headers.join(','), ...logs.map(l => headers.map(h => JSON.stringify(l[h] || '')).join(','))].join('\n');
    const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));
    const a = document.createElement('a'); a.href = url; a.download = 'bus-drive-log.csv'; a.click(); URL.revokeObjectURL(url);
  };
  return <main className="panel wide"><div className="toolbar"><h2>Bus history</h2><button className="button secondary" onClick={onRefresh}><RefreshCw size={16}/> Refresh</button><button className="button secondary" onClick={exportCsv}><Download size={16}/> Export CSV</button></div><div className="search"><Search size={18}/><input value={query} onChange={e=>setQuery(e.target.value)} placeholder="Search fleet, rego, shift, notes..." /></div><div className="stats"><b>{logs.length}</b> total logs <b>{new Set(logs.map(l=>l.fleetNumber)).size}</b> unique buses <b>{logs.filter(l=>l.aircon==='Bad').length}</b> bad aircon notes</div>{filtered.map(log => <article className="logCard" key={log.id}><div><h3>{log.fleetNumber || 'Unknown bus'} <span>{log.registration}</span></h3><p>{log.date} {log.time} • {log.shiftType} {log.shiftNumber && `• Shift ${log.shiftNumber}`}</p><p>{log.vehicleDescription} {log.vehicleLocation && `• ${log.vehicleLocation}`}</p></div><div className="chips"><span>Gear: {log.gearNoise || '-'}</span><span>Power: {log.power || '-'}</span><span>Rattles: {log.bodyRattles || '-'}</span><span>Aircon: {log.aircon || '-'}</span></div>{log.damageNotes && <p><b>Damage/defect:</b> {log.damageNotes}</p>}{log.comments && <p><b>Comments:</b> {log.comments}</p>}<div className="fileLinks">{log.photoUrl && <a href={log.photoUrl} target="_blank" rel="noreferrer"><Camera size={16}/> {log.photoName || 'Photo'}</a>}{log.runPrintUrl && <a href={log.runPrintUrl} target="_blank" rel="noreferrer"><FileText size={16}/> {log.runPrintName || 'Run print'}</a>}<button className="iconButton" onClick={()=>onDelete(log.id)}><Trash2 size={16}/> Delete</button></div></article>)}{filtered.length === 0 && <p className="empty">No matching logs yet.</p>}</main>;
}
function FleetRegister({ vehicles }) {
  const [query, setQuery] = useState('');
  const filtered = vehicles.filter(v => JSON.stringify(v).toLowerCase().includes(query.toLowerCase())).slice(0, 300);
  return <main className="panel wide"><h2>Fleet register</h2><p className="hint">Loaded from the uploaded spreadsheet. Showing up to 300 matches.</p><div className="search"><Search size={18}/><input value={query} onChange={e=>setQuery(e.target.value)} placeholder="Search fleet, rego, model, depot..." /></div><table><thead><tr><th>Fleet</th><th>Rego</th><th>Description</th><th>Location</th><th>Status</th></tr></thead><tbody>{filtered.map(v => <tr key={v.fleetNumber}><td>{v.fleetNumber}</td><td>{v.registration}</td><td>{v.description}</td><td>{v.location}</td><td>{v.status}</td></tr>)}</tbody></table></main>;
}
function HomeScreen({ setPage }) { return <main className="homeGrid"><button onClick={()=>setPage('log')} className="homeCard"><ClipboardList/><b>Log today’s bus</b><span>Phone-friendly vehicle and shift entry</span></button><button onClick={()=>setPage('history')} className="homeCard"><Database/><b>View bus history</b><span>Search all buses, defects, photos and run prints</span></button><button onClick={()=>setPage('fleet')} className="homeCard"><Bus/><b>Fleet register</b><span>{fleetVehicles.length} fleet entries loaded</span></button></main>; }
function App() {
  const [page, setPage] = useState('home');
  const [logs, setLogs] = useState([]);
  const [error, setError] = useState('');
  const fleetIndex = useMemo(() => new Map(fleetVehicles.map(v => [normaliseFleet(v.fleetNumber), v])), []);
  const refresh = async () => { try { setLogs(await loadLogs()); setError(''); } catch(e) { setError(e.message); } };
  useEffect(()=>{ refresh(); }, []);
  const remove = async id => { if (confirm('Delete this log?')) { await deleteLog(id); await refresh(); } };
  return <div><header><div className="brand"><Bus/><div><h1>Bus Drive Log</h1><p>{supabase ? 'Supabase cloud sync enabled' : 'Local demo mode — add Supabase env vars for phone/computer sync'}</p></div></div><nav><button className={page==='home'?'active':''} onClick={()=>setPage('home')}><Home size={16}/>Home</button><button className={page==='log'?'active':''} onClick={()=>setPage('log')}>Log</button><button className={page==='history'?'active':''} onClick={()=>setPage('history')}>History</button><button className={page==='fleet'?'active':''} onClick={()=>setPage('fleet')}>Fleet</button></nav></header>{error && <div className="banner">{error}</div>}{page==='home' && <HomeScreen setPage={setPage}/>} {page==='log' && <LogBus fleetIndex={fleetIndex} onSaved={refresh}/>} {page==='history' && <History logs={logs} onRefresh={refresh} onDelete={remove}/>} {page==='fleet' && <FleetRegister vehicles={fleetVehicles}/>}<footer>QLD Rego Check is linked for manual verification only.</footer></div>;
}

createRoot(document.getElementById('root')).render(<App />);
