'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'

export default function Dashboard() {
  const [token, setToken] = useState('')
  const [apiKey, setApiKey] = useState('')
  const [url, setUrl] = useState('https://example.com')
  const [endpoint, setEndpoint] = useState('screenshot')
  const [result, setResult] = useState('')
  const [loading, setLoading] = useState(false)
  const [apiKeys, setApiKeys] = useState<{id: string, name: string}[]>([])
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [isLoggedIn, setIsLoggedIn] = useState(false)
  const [newKeyName, setNewKeyName] = useState('')

  const endpoints = ['crawl', 'content', 'screenshot', 'pdf', 'markdown', 'snapshot', 'scrape', 'json', 'links']

  useEffect(() => {
    const saved = localStorage.getItem('crawlapi_token')
    if (saved) {
      setToken(saved)
      setIsLoggedIn(true)
      fetchApiKeys(saved)
    }
  }, [])

  async function login() {
    try {
      const res = await fetch('http://localhost:3000/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      })
      const data = await res.json()
      if (data.token) {
        setToken(data.token)
        setIsLoggedIn(true)
        localStorage.setItem('crawlapi_token', data.token)
        fetchApiKeys(data.token)
      } else {
        setResult(JSON.stringify(data, null, 2))
      }
    } catch (e) {
      setResult(String(e))
    }
  }

  async function fetchApiKeys(t: string) {
    try {
      const res = await fetch('http://localhost:3000/api/auth/api-keys', {
        headers: { 'x-auth-token': t },
      })
      const data = await res.json()
      setApiKeys(data || [])
    } catch (e) {
      console.error(e)
    }
  }

  async function createApiKey() {
    try {
      const res = await fetch('http://localhost:3000/api/auth/api-keys', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-auth-token': token,
        },
        body: JSON.stringify({ name: newKeyName || 'New Key' }),
      })
      const data = await res.json()
      setResult(JSON.stringify(data, null, 2))
      fetchApiKeys(token)
    } catch (e) {
      setResult(String(e))
    }
  }

  async function testApi() {
    setLoading(true)
    try {
      const res = await fetch(`http://localhost:3000/api/${endpoint}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-api-key': apiKey,
        },
        body: JSON.stringify({ url }),
      })
      const data = await res.json()
      setResult(JSON.stringify(data, null, 2))
    } catch (e) {
      setResult(String(e))
    } finally {
      setLoading(false)
    }
  }

  return (
    <main style={{ maxWidth: 1200, margin: '0 auto', padding: '40px 20px' }}>
      <nav style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 60 }}>
        <Link href="/" style={{ fontSize: 24, fontWeight: 700, color: '#fff', textDecoration: 'none' }}>Crawl API</Link>
        <Link href="/" style={{ color: '#888', textDecoration: 'none' }}>← Back</Link>
      </nav>

      <h1 style={{ fontSize: 36, marginBottom: 8 }}>Dashboard</h1>
      <p style={{ color: '#888', marginBottom: 40 }}>Test your API keys and monitor usage.</p>

      {!isLoggedIn ? (
        <div style={{ background: '#111', borderRadius: 12, padding: 24, marginBottom: 24 }}>
          <h3 style={{ marginTop: 0 }}>Login</h3>
          <button
            onClick={async () => {
              const res = await fetch('http://localhost:3000/api/auth/google')
              const data = await res.json()
              if (data.url) window.location.href = data.url
            }}
            style={{
              background: '#4285f4',
              color: '#fff',
              padding: '12px 24px',
              borderRadius: 8,
              border: 'none',
              fontWeight: 600,
              cursor: 'pointer',
              marginBottom: 16,
              width: '100%'
            }}
          >
            Sign in with Google
          </button>
          <div style={{ color: '#888', textAlign: 'center', marginBottom: 16 }}>or</div>
          <div style={{ display: 'grid', gap: 16, marginBottom: 16 }}>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="demo@crawlapi.dev"
              style={{
                width: '100%',
                padding: 12,
                background: '#1a1a1a',
                border: '1px solid #333',
                borderRadius: 8,
                color: '#fff',
                fontSize: 14,
                boxSizing: 'border-box'
              }}
            />
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="password"
              style={{
                width: '100%',
                padding: 12,
                background: '#1a1a1a',
                border: '1px solid #333',
                borderRadius: 8,
                color: '#fff',
                fontSize: 14,
                boxSizing: 'border-box'
              }}
            />
          </div>
          <button
            onClick={login}
            style={{
              background: '#fff',
              color: '#000',
              padding: '12px 24px',
              borderRadius: 8,
              border: 'none',
              fontWeight: 600,
              cursor: 'pointer'
            }}
          >
            Login
          </button>
        </div>
      ) : (
        <>
          <div style={{ background: '#111', borderRadius: 12, padding: 24, marginBottom: 24 }}>
            <h3 style={{ marginTop: 0 }}>Your API Keys</h3>
            <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
              <input
                type="text"
                value={newKeyName}
                onChange={(e) => setNewKeyName(e.target.value)}
                placeholder="Key name"
                style={{
                  flex: 1,
                  padding: 12,
                  background: '#1a1a1a',
                  border: '1px solid #333',
                  borderRadius: 8,
                  color: '#fff',
                  fontSize: 14,
                }}
              />
              <button
                onClick={createApiKey}
                style={{
                  background: '#fff',
                  color: '#000',
                  padding: '12px 24px',
                  borderRadius: 8,
                  border: 'none',
                  fontWeight: 600,
                  cursor: 'pointer'
                }}
              >
                Create Key
              </button>
            </div>
            {apiKeys.length > 0 ? (
              <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                {apiKeys.map((k) => (
                  <li key={k.id} style={{ padding: '8px 0', borderBottom: '1px solid #222', color: '#888' }}>
                    {k.name} <span style={{ fontFamily: 'monospace', fontSize: 12 }}>({k.id})</span>
                  </li>
                ))}
              </ul>
            ) : (
              <p style={{ color: '#888' }}>No API keys yet. Create one above.</p>
            )}
          </div>

          <div style={{ background: '#111', borderRadius: 12, padding: 24, marginBottom: 24 }}>
            <h3 style={{ marginTop: 0 }}>Test API</h3>
            <div style={{ display: 'grid', gap: 16, marginBottom: 16 }}>
              <div>
                <label style={{ display: 'block', color: '#888', marginBottom: 8, fontSize: 14 }}>API Key</label>
                <input
                  type="text"
                  value={apiKey}
                  onChange={(e) => setApiKey(e.target.value)}
                  placeholder="your-api-key"
                  style={{
                    width: '100%',
                    padding: 12,
                    background: '#1a1a1a',
                    border: '1px solid #333',
                    borderRadius: 8,
                    color: '#fff',
                    fontSize: 14,
                    boxSizing: 'border-box'
                  }}
                />
              </div>
              <div>
                <label style={{ display: 'block', color: '#888', marginBottom: 8, fontSize: 14 }}>URL</label>
                <input
                  type="text"
                  value={url}
                  onChange={(e) => setUrl(e.target.value)}
                  style={{
                    width: '100%',
                    padding: 12,
                    background: '#1a1a1a',
                    border: '1px solid #333',
                    borderRadius: 8,
                    color: '#fff',
                    fontSize: 14,
                    boxSizing: 'border-box'
                  }}
                />
              </div>
              <div>
                <label style={{ display: 'block', color: '#888', marginBottom: 8, fontSize: 14 }}>Endpoint</label>
                <select
                  value={endpoint}
                  onChange={(e) => setEndpoint(e.target.value)}
                  style={{
                    width: '100%',
                    padding: 12,
                    background: '#1a1a1a',
                    border: '1px solid #333',
                    borderRadius: 8,
                    color: '#fff',
                    fontSize: 14
                  }}
                >
                  {endpoints.map((ep) => (
                    <option key={ep} value={ep}>{ep}</option>
                  ))}
                </select>
              </div>
            </div>
            <button
              onClick={testApi}
              disabled={loading}
              style={{
                background: loading ? '#333' : '#fff',
                color: '#000',
                padding: '12px 24px',
                borderRadius: 8,
                border: 'none',
                fontWeight: 600,
                cursor: loading ? 'not-allowed' : 'pointer'
              }}
            >
              {loading ? 'Sending...' : 'Send Request'}
            </button>
          </div>
        </>
      )}

      {result && (
        <div style={{ background: '#111', borderRadius: 12, padding: 24 }}>
          <h3 style={{ marginTop: 0 }}>Response</h3>
          <pre style={{ margin: 0, overflow: 'auto', fontSize: 13 }}>{result}</pre>
        </div>
      )}
    </main>
  )
}
