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

const bridge = window.mixone || {}

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

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

function Btn({ label, onPress, primary, danger, style }) {
  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 }) {
  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(null)
  const [fileContent, setFileContent] = useState('')
  const [filePath, setFilePath] = useState('')
  const [clipText, setClipText] = useState('')
  const [inputText, setInputText] = useState('Hello from mixone!')

  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>}

      <Text style={s.h1}>{{appName}}</Text>
      <Text style={s.sub}>RN components rendered to browser · mixone IPC full demo</Text>

      <View style={s.statGrid}>
        <View style={s.statBox}><Text style={s.statVal}>{bridge.version || '-'}</Text><Text style={s.statLbl}>Electron</Text></View>
        <View style={s.statBox}><Text style={s.statVal}>{bridge.chrome || '-'}</Text><Text style={s.statLbl}>Chromium</Text></View>
        <View style={s.statBox}><Text style={s.statVal}>{bridge.node || '-'}</Text><Text style={s.statLbl}>Node.js</Text></View>
        <View style={s.statBox}><Text style={s.statVal}>{bridge.platform || '-'}</Text><Text style={s.statLbl}>Platform</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>
    </ScrollView>
  )
}

const s = StyleSheet.create({
  page: { flex: 1, padding: 24 },
  h1: { fontSize: 22, fontWeight: '600', color: '#e2e8f0', marginBottom: 4 },
  sub: { fontSize: 13, color: '#94a3b8', marginBottom: 20 },
  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' },
  statVal: { fontSize: 18, 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' },
  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' }
})