import React, { useState, useEffect } from 'react'
import { View, Text, TextInput, Pressable, ScrollView, StyleSheet } from 'react-native'

const bridge = (window as any).{{bridgeGlobal}} || {}

function showToast(setToast: any, msg: string, type = 'info') {
  setToast({ msg, type })
  setTimeout(() => setToast(null), 2500)
}

function Card({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <View style={s.card}>
      <Text style={s.cardTitle}>{title}</Text>
      {children}
    </View>
  )
}

function Btn({ label, onPress, primary, danger, style }: { label: string; onPress: () => void; primary?: boolean; danger?: boolean; style?: any }) {
  return (
    <Pressable style={[s.btn, primary && s.btnPrimary, danger && s.btnDanger, style]} onPress={onPress}>
      <Text style={[s.btnText, primary && s.btnTextPrimary]}>{label}</Text>
    </Pressable>
  )
}

function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <View style={s.infoRow}>
      <Text style={s.infoLabel}>{label}</Text>
      <Text style={s.infoValue}>{value}</Text>
    </View>
  )
}

export default function Home() {
  const [toast, setToast] = useState<{ msg: string; type: string } | null>(null)
  const [fileContent, setFileContent] = useState('')
  const [filePath, setFilePath] = useState('')
  const [clipText, setClipText] = useState('')
  const [inputText, setInputText] = useState('Hello from mixone!')
  const [time, setTime] = useState(new Date().toLocaleTimeString())

  useEffect(() => {
    const timer = setInterval(() => setTime(new Date().toLocaleTimeString()), 1000)
    return () => clearInterval(timer)
  }, [])

  async function openFile() {
    const r = await bridge.dialog?.openFile({ title: 'Select file', filters: [{ name: 'All', extensions: ['*'] }] })
    if (r?.canceled || !r?.filePaths?.length) return
    setFilePath(r.filePaths[0])
    const data = await bridge.fs?.readText(r.filePaths[0])
    if (data) { setFileContent(data.content); showToast(setToast, `Read ${data.size} bytes`, 'success') }
  }

  async function saveFile() {
    const r = await bridge.dialog?.saveFile({ title: 'Save file', defaultPath: 'untitled.txt' })
    if (r?.canceled || !r?.filePath) return
    const d = await bridge.fs?.writeText(r.filePath, fileContent)
    if (d) showToast(setToast, `Saved ${d.bytesWritten} bytes`, 'success')
  }

  async function messageBox() {
    const r = await bridge.dialog?.messageBox({ type: 'question', title: 'Confirm', message: 'Message dialog demo', buttons: ['Cancel', 'OK'] })
    showToast(setToast, `Button #${r?.response}`, 'info')
  }

  async function readClip() { const t = await bridge.clipboard?.readText(); setClipText(t || '(empty)'); showToast(setToast, 'Read clipboard', 'success') }
  async function writeClip() { await bridge.clipboard?.writeText(inputText); showToast(setToast, 'Wrote clipboard', 'success'); await readClip() }
  async function clearClip() { await bridge.clipboard?.clear(); setClipText('(cleared)'); showToast(setToast, 'Cleared clipboard', 'success') }

  return (
    <ScrollView style={s.page}>
      {toast && <View style={[s.toast, toast.type === 'success' ? s.toastSuccess : s.toastInfo]}><Text style={s.toastText}>{toast.msg}</Text></View>}

      <View style={s.hero}>
        <Text style={s.heroBadge}>⚡ Powered by mixone</Text>
        <Text style={s.heroTitle}>{{appName}}</Text>
        <Text style={s.heroSub}>React Native Web + TypeScript + Electron</Text>
        <Text style={s.heroTime}>{time}</Text>
      </View>

      <View style={s.statGrid}>
        {[{ val: bridge.version, lbl: 'Electron', icon: '⚡' }, { val: bridge.chrome, lbl: 'Chromium', icon: '🌐' }, { val: bridge.node, lbl: 'Node.js', icon: '📦' }, { val: bridge.platform, lbl: 'Platform', icon: '💻' }].map(s => (
          <View style={s.statBox} key={s.lbl}>
            <Text style={s.statIcon}>{s.icon}</Text>
            <Text style={s.statVal}>{s.val || '-'}</Text>
            <Text style={s.statLbl}>{s.lbl}</Text>
          </View>
        ))}
      </View>

      <Card title="📁 File Dialog & Filesystem">
        <View style={s.btnGroup}>
          <Btn label="📂 Open file" primary onPress={openFile} />
          <Btn label="💾 Save file" onPress={saveFile} />
        </View>
        {filePath ? <InfoRow label="Current file" value={filePath} /> : null}
        <TextInput style={s.textarea} multiline value={fileContent} onChangeText={setFileContent} placeholder="File content..." />
      </Card>

      <Card title="💬 Message Dialog">
        <Btn label="Open message dialog" onPress={messageBox} />
      </Card>

      <Card title="📋 Clipboard">
        <View style={{ flexDirection: 'row', gap: 8, marginBottom: 12 }}>
          <TextInput style={[s.input, { flex: 1 }]} value={inputText} onChangeText={setInputText} placeholder="Input text..." />
          <Btn label="Write" primary onPress={writeClip} />
        </View>
        <InfoRow label="Clipboard" value={clipText} />
        <View style={s.btnGroup}>
          <Btn label="🔄 Read" onPress={readClip} />
          <Btn label="🗑️ Clear" danger onPress={clearClip} />
        </View>
      </Card>

      <Card title="🪟 Window Management">
        <View style={s.btnGroup}>
          <Btn label="📄 Child window" onPress={() => { bridge.window?.open({ url: location.origin + location.pathname + '#/about', width: 600, height: 400 }); showToast(setToast, 'Opened', 'success') }} />
          <Btn label="🔒 Modal" onPress={() => bridge.window?.openModal({ url: location.origin + location.pathname + '#/about', width: 520, height: 420 })} />
          <Btn label="🔼 Maximize" onPress={async () => { const r = await bridge.window?.maximize(); showToast(setToast, r?.maximized ? 'Maximized' : 'Restored', 'info') }} />
          <Btn label="⬇️ Minimize" onPress={() => bridge.window?.minimize()} />
          <Btn label="✕ Close" danger onPress={() => bridge.window?.close()} />
        </View>
      </Card>

      <Card title="🔗 Shell Integration">
        <View style={s.btnGroup}>
          <Btn label="🌐 GitHub" onPress={() => bridge.shell?.openExternal('https://github.com/qew4/mixone-example')} />
          <Btn label="📦 npm" onPress={() => bridge.shell?.openExternal('https://www.npmjs.com/package/mixone')} />
          <Btn label="🔔 Beep" onPress={() => bridge.shell?.beep()} />
        </View>
      </Card>

      <Card title="📖 API Reference">
        <InfoRow label="bridge.dialog.openFile(opts)" value="File dialog" />
        <InfoRow label="bridge.fs.readText(path)" value="Read file" />
        <InfoRow label="bridge.clipboard.writeText(text)" value="Write clipboard" />
        <InfoRow label="bridge.window.open(opts)" value="New window" />
        <InfoRow label="bridge.shell.openExternal(url)" value="Open URL" />
        <InfoRow label="bridge.app.info()" value="App info" />
      </Card>
    </ScrollView>
  )
}

const s = StyleSheet.create({
  page: { flex: 1, padding: 24 },
  hero: { alignItems: 'center', marginBottom: 24, paddingVertical: 32, backgroundColor: 'rgba(56,189,248,0.05)', borderRadius: 16, marginHorizontal: -24, marginTop: -24 },
  heroBadge: { fontSize: 12, color: '#38bdf8', backgroundColor: 'rgba(56,189,248,0.15)', paddingHorizontal: 12, paddingVertical: 4, borderRadius: 20, marginBottom: 12 },
  heroTitle: { fontSize: 28, fontWeight: '700', color: '#38bdf8', marginBottom: 8 },
  heroSub: { fontSize: 14, color: '#94a3b8', marginBottom: 8 },
  heroTime: { fontSize: 14, color: '#38bdf8', fontFamily: 'monospace' },
  statGrid: { flexDirection: 'row', gap: 12, marginBottom: 20 },
  statBox: { flex: 1, backgroundColor: 'rgba(56,189,248,0.05)', borderWidth: 1, borderColor: 'rgba(56,189,248,0.15)', borderRadius: 10, padding: 14, alignItems: 'center' },
  statIcon: { fontSize: 20, marginBottom: 4 },
  statVal: { fontSize: 16, fontWeight: '700', color: '#38bdf8', fontFamily: 'monospace' },
  statLbl: { fontSize: 11, color: '#94a3b8', marginTop: 4 },
  card: { backgroundColor: '#1e293b', borderWidth: 1, borderColor: '#334155', borderRadius: 12, padding: 20, marginBottom: 16 },
  cardTitle: { fontSize: 14, fontWeight: '600', color: '#38bdf8', marginBottom: 16 },
  infoRow: { flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 8, borderBottomWidth: 1, borderBottomColor: 'rgba(255,255,255,0.05)' },
  infoLabel: { color: '#94a3b8', fontSize: 13 },
  infoValue: { fontFamily: 'monospace', fontSize: 12, color: '#e2e8f0', maxWidth: '60%' },
  btnGroup: { flexDirection: 'row', gap: 8, flexWrap: 'wrap', marginBottom: 8 },
  btn: { backgroundColor: '#1e293b', borderWidth: 1, borderColor: '#334155', borderRadius: 8, paddingVertical: 8, paddingHorizontal: 16 },
  btnPrimary: { backgroundColor: '#38bdf8', borderColor: '#38bdf8' },
  btnDanger: { borderColor: '#f87171' },
  btnText: { color: '#e2e8f0', fontSize: 13 },
  btnTextPrimary: { color: '#0f172a', fontWeight: '500' },
  textarea: { width: '100%', minHeight: 80, backgroundColor: '#0f172a', borderWidth: 1, borderColor: '#334155', borderRadius: 8, padding: 12, color: '#e2e8f0', fontFamily: 'monospace', fontSize: 13, textAlignVertical: 'top' },
  input: { height: 40, backgroundColor: '#0f172a', borderWidth: 1, borderColor: '#334155', borderRadius: 8, paddingHorizontal: 12, color: '#e2e8f0' },
  toast: { position: 'absolute', top: 16, right: 16, paddingVertical: 10, paddingHorizontal: 16, borderRadius: 8, zIndex: 999 },
  toastSuccess: { backgroundColor: 'rgba(74,222,128,0.15)', borderWidth: 1, borderColor: '#4ade80' },
  toastInfo: { backgroundColor: 'rgba(56,189,248,0.15)', borderWidth: 1, borderColor: '#38bdf8' },
  toastText: { fontSize: 13, color: '#e2e8f0' }
})