import { useState, useEffect } from 'react'
import { FaFileLines } from 'react-icons/fa6'
import ReactMarkdown from 'react-markdown'
import { fetchProjectReadme } from '../lib/projectAdminApi'

const markdownComponents = {
  h1: ({ children }) => <h1 style={{ fontSize: '1.35rem', fontWeight: 700, margin: '0 0 10px', color: '#f8fafc' }}>{children}</h1>,
  h2: ({ children }) => <h2 style={{ fontSize: '1.15rem', fontWeight: 700, margin: '14px 0 8px', color: '#f1f5f9' }}>{children}</h2>,
  h3: ({ children }) => <h3 style={{ fontSize: '1rem', fontWeight: 600, margin: '12px 0 6px', color: '#e2e8f0' }}>{children}</h3>,
  p: ({ children }) => <p style={{ margin: '0 0 10px', lineHeight: 1.6 }}>{children}</p>,
  ul: ({ children }) => <ul style={{ margin: '0 0 10px', paddingLeft: 20 }}>{children}</ul>,
  ol: ({ children }) => <ol style={{ margin: '0 0 10px', paddingLeft: 20 }}>{children}</ol>,
  code: ({ inline, children }) => inline ? (
    <code style={{ background: 'rgba(30,41,59,0.9)', padding: '2px 6px', borderRadius: 4, fontSize: '0.9em' }}>{children}</code>
  ) : <code>{children}</code>,
  pre: ({ children }) => <pre style={{ background: 'rgba(15,23,42,0.95)', borderRadius: 6, padding: 10, overflowX: 'auto', margin: '0 0 10px' }}>{children}</pre>,
  a: ({ href, children }) => <a href={href} target="_blank" rel="noopener noreferrer" style={{ color: '#60a5fa' }}>{children}</a>,
}

export default function ProjectReadme({ repoFullName }) {
  const [state, setState] = useState({ loading: true, content: '', filename: '', error: '' })

  useEffect(() => {
    if (!repoFullName) { setState({ loading: false, content: '', filename: '', error: '' }); return }
    let cancelled = false
    setState({ loading: true, content: '', filename: '', error: '' })
    fetchProjectReadme(repoFullName)
      .then((data) => {
        if (cancelled) return
        if (!data.found) { setState({ loading: false, content: '', filename: '', error: '' }); return }
        setState({ loading: false, content: data.content || '', filename: data.filename || 'README.md', error: '' })
      })
      .catch((err) => { if (!cancelled) setState({ loading: false, content: '', filename: '', error: err.message }) })
    return () => { cancelled = true }
  }, [repoFullName])

  if (state.loading) return <p className="text-grey" style={{ fontSize: 13, marginTop: 8 }}>README wird geladen...</p>
  if (state.error || !state.content) return null

  return (
    <div style={{ marginTop: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6, fontSize: 13, color: '#94a3b8' }}>
        <FaFileLines /><span>{state.filename}</span>
      </div>
      <div style={{ background: 'rgba(15,23,42,0.6)', border: '1px solid rgba(148,163,184,0.2)', borderRadius: 8, padding: '12px 14px', fontSize: 13, color: '#e2e8f0', maxHeight: 320, overflowY: 'auto' }}>
        <ReactMarkdown components={markdownComponents}>{state.content}</ReactMarkdown>
      </div>
    </div>
  )
}
