"use client"

import { useEffect, useId, useRef, useState, type ReactNode } from "react"
import { NOTES, type DraftReport as ReportData } from "@/examples/brindlefen-demo/src/report"
import voice from "@/examples/brindlefen-demo/results/voice-run.json"
import s from "./demo-pieces.module.css"

export function JobScreen({ children, status = "Job report · Draft", compact = false }: { children: ReactNode; status?: string; compact?: boolean }) {
  return <div className={s.frame} data-component="JobScreen" data-compact={compact}><div className={s.appbar}><span className={s.wordmark}><span className={s.mark} aria-hidden="true" />Brindlefen</span><span>{status}</span></div><div className={s.appbody}><h3>Radiator valve replacement</h3>{compact ? null : <p className={s.notice}>Alex at the job. Robin at home. Fictional people and work.</p>}{children}</div></div>
}

export function BeforeVoiceReports({ note }: { note: string }) {
  const id = useId()
  return <JobScreen compact status="Before · Job details"><div data-component="BeforeVoiceReports"><dl className={s.jobDetails}><dt>Engineer</dt><dd>Alex</dd><dt>Homeowner</dt><dd>Robin</dd><dt>Work</dt><dd>Radiator valve replacement</dd></dl><div className={s.note}><label htmlFor={id}>Job notes</label><textarea id={id} value={note} readOnly /></div><p className={s.notice}>A plain job note. The report still has to be written separately.</p></div></JobScreen>
}

export function NoteInput({ note, onChange, onDraft }: { note: string; onChange: (value: string) => void; onDraft: () => void }) {
  const id = useId()
  const [recording, setRecording] = useState(false)
  const [audio, setAudio] = useState("")
  const [audioMessage, setAudioMessage] = useState("")
  const recorder = useRef<MediaRecorder | null>(null)
  const audioUrl = useRef("")
  const stream = useRef<MediaStream | null>(null)
  useEffect(() => () => {
    stream.current?.getTracks().forEach((track) => track.stop())
    if (audioUrl.current) URL.revokeObjectURL(audioUrl.current)
  }, [])

  async function record() {
    if (recording) { recorder.current?.stop(); setRecording(false); return }
    if (!window.isSecureContext || !navigator.mediaDevices?.getUserMedia || typeof MediaRecorder === "undefined") {
      setAudioMessage("Audio recording needs a secure browser connection. You can edit the example transcript below.")
      return
    }
    try {
      const media = await navigator.mediaDevices.getUserMedia({ audio: true })
      stream.current = media
      const chunks: BlobPart[] = []
      const rec = new MediaRecorder(media)
      recorder.current = rec
      rec.ondataavailable = (event) => { if (event.data.size) chunks.push(event.data) }
      rec.onstop = () => {
        if (audioUrl.current) URL.revokeObjectURL(audioUrl.current)
        audioUrl.current = URL.createObjectURL(new Blob(chunks, { type: rec.mimeType }))
        setAudio(audioUrl.current)
        media.getTracks().forEach((track) => track.stop())
        setAudioMessage("Recording stays in this browser. Listen back, then type the words into the transcript. No transcription service is connected.")
      }
      rec.start()
      setRecording(true)
      setAudioMessage("Recording locally. Choose Stop recording when you finish.")
    } catch { setAudioMessage("Microphone access was unavailable. You can edit the example transcript below.") }
  }

  return <div className={s.note} data-component="NoteInput"><label htmlFor={id}>Voice note transcript</label><textarea id={id} value={note} onChange={(event) => onChange(event.target.value)} /><div className={s.actions}><button className={s.button} onClick={onDraft}>Draft the report</button><button className={s.quiet} onClick={() => void record()}>{recording ? "Stop recording" : "Record a note"}</button></div><div className={s.actions} aria-label="Example notes"><button className={s.quiet} onClick={() => onChange(voice.transcript)}>Use the real transcript</button><button className={s.quiet} onClick={() => onChange(NOTES.service)}>Boiler service note</button><button className={s.quiet} onClick={() => onChange(NOTES.unclear)}>Unclear note</button></div>{audio ? <audio className={s.audio} src={audio} controls aria-label="Your local voice recording" /> : null}<p className={s.notice} role="status">{audioMessage || "Edit the fictional note or record audio for local playback."}</p><details><summary>Listen to the voice fixture</summary><audio className={s.audio} src="/why-first/brindlefen/valve-note.mp3" controls preload="none" aria-label="Fictional voice note, spoken by a synthetic voice" /><p className={s.notice}>{voice.source} {voice.limitation}</p></details></div>
}

export function DraftReport({ report, onEdit, compact = false }: { report: ReportData; onEdit?: (key: "work" | "homeowner", value: string) => void; compact?: boolean }) {
  const id = useId()
  if (report.needsClarification) return <div className={s.report} data-component="DraftReport"><h3>A clearer note is needed.</h3><p>{report.followUp}</p></div>
  return <div className={s.report} data-component="DraftReport">{onEdit ? <div className={s.field}><label htmlFor={`${id}-work`}>Work recorded</label><textarea id={`${id}-work`} value={report.work} onChange={(event) => onEdit("work", event.target.value)} /></div> : <dl><dt>Work recorded</dt><dd>{report.work}</dd></dl>}<dl><dt>Parts from the list</dt><dd>{report.parts.join(", ") || "None recorded"}</dd><dt>Safety result</dt><dd>{report.safety}</dd><dt>Follow-up</dt><dd>{report.followUp || "None recorded"}</dd></dl>{onEdit ? <div className={s.field}><label htmlFor={`${id}-summary`}>Homeowner summary</label><textarea id={`${id}-summary`} value={report.homeowner} onChange={(event) => onEdit("homeowner", event.target.value)} /></div> : compact ? null : <dl><dt>Homeowner summary</dt><dd>{report.homeowner}</dd></dl>}</div>
}

export function ReviewControl({ reviewed, stale, onReviewed, onSave, onReset }: { reviewed: boolean; stale: boolean; onReviewed: (value: boolean) => void; onSave: () => void; onReset: () => void }) {
  return <div data-component="ReviewControl">{stale ? <p className={s.notice}>The note has changed. Draft the report again before reviewing it.</p> : null}<label className={s.review}><input type="checkbox" checked={reviewed} disabled={stale} onChange={(event) => onReviewed(event.target.checked)} /><span>I have checked this draft against the note.</span></label><div className={s.actions}><button className={s.button} disabled={!reviewed || stale} onClick={onSave}>Add to local outbox</button><button className={s.quiet} onClick={onReset}>Reset example</button></div></div>
}

export function LocalOutbox({ report }: { report: string }) {
  if (!report) return null
  return <div className={s.outbox} role="status" data-component="LocalOutbox"><h3>Saved in the local outbox.</h3><p>Nothing has been sent.</p><details><summary>Read the saved report</summary><pre>{report}</pre></details></div>
}
