import { useState } from 'react'
import type { TraceFile } from '../../types/trace'
import { traceDatabase } from '../utils/traceDatabase'

interface TraceUploadProps {
  onUploadSuccess: (traceId: string) => void
}

export default function TraceUpload({ onUploadSuccess }: TraceUploadProps) {
  const [uploading, setUploading] = useState(false)
  const [dragOver, setDragOver] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const validateTraceFile = (data: any): data is TraceFile => {
    return data && 
           data.metadata && 
           Array.isArray(data.traceEvents) && 
           data.traceEvents.length > 0
  }

  const processFile = async (file: File) => {
    setUploading(true)
    setError(null)

    try {
      // Validate file type
      if (!file.name.toLowerCase().endsWith('.json')) {
        throw new Error('Please upload a JSON trace file')
      }

      // Validate file size (max 200MB)
      if (file.size > 200 * 1024 * 1024) {
        throw new Error('Trace file too large (max 200MB)')
      }

      // Read file content
      const text = await file.text()
      
      // Parse JSON
      let traceData: TraceFile
      try {
        traceData = JSON.parse(text)
      } catch (parseError) {
        throw new Error('Invalid JSON format')
      }

      // Validate trace structure
      if (!validateTraceFile(traceData)) {
        throw new Error('Invalid trace file format. Expected Chrome DevTools Performance trace.')
      }

      // Store in database
      const traceId = await traceDatabase.addTrace(traceData, file.name, file.size)
      
      onUploadSuccess(traceId)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Upload failed')
    } finally {
      setUploading(false)
    }
  }

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      processFile(file)
    }
  }

  const handleDrop = (event: React.DragEvent) => {
    event.preventDefault()
    setDragOver(false)
    
    const file = event.dataTransfer.files[0]
    if (file) {
      processFile(file)
    }
  }

  const handleDragOver = (event: React.DragEvent) => {
    event.preventDefault()
    setDragOver(true)
  }

  const handleDragLeave = (event: React.DragEvent) => {
    event.preventDefault()
    setDragOver(false)
  }

  return (
    <div style={{ 
      display: 'flex', 
      flexDirection: 'column', 
      alignItems: 'center', 
      justifyContent: 'center',
      minHeight: '400px',
      padding: '40px',
      fontFamily: 'system-ui, sans-serif'
    }}>
      <div style={{
        maxWidth: '600px',
        textAlign: 'center',
        marginBottom: '30px'
      }}>
        <h1 style={{ 
          fontSize: '28px', 
          color: '#495057', 
          marginBottom: '16px',
          fontWeight: '600'
        }}>
          Performance Trace Analyzer
        </h1>
        <p style={{ 
          fontSize: '16px', 
          color: '#6c757d', 
          lineHeight: '1.5',
          marginBottom: '24px'
        }}>
          Upload Chrome DevTools Performance trace files to analyze network requests, 
          queue times, CDN usage, and performance bottlenecks.
        </p>
      </div>

      <div
        style={{
          border: dragOver ? '2px dashed #007bff' : '2px dashed #dee2e6',
          borderRadius: '12px',
          padding: '40px',
          backgroundColor: dragOver ? '#f8f9ff' : '#f8f9fa',
          transition: 'all 0.2s ease',
          cursor: 'pointer',
          minWidth: '400px',
          textAlign: 'center'
        }}
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onClick={() => document.getElementById('trace-upload')?.click()}
      >
        {uploading ? (
          <div>
            <div style={{
              width: '40px',
              height: '40px',
              border: '4px solid #f3f3f3',
              borderTop: '4px solid #007bff',
              borderRadius: '50%',
              animation: 'spin 1s linear infinite',
              margin: '0 auto 20px'
            }} />
            <div style={{ fontSize: '16px', color: '#495057' }}>
              Processing trace file...
            </div>
          </div>
        ) : (
          <div>
            <div style={{ fontSize: '48px', marginBottom: '16px' }}>📊</div>
            <div style={{ 
              fontSize: '18px', 
              fontWeight: '600', 
              color: '#495057',
              marginBottom: '8px'
            }}>
              Drop your trace file here
            </div>
            <div style={{ 
              fontSize: '14px', 
              color: '#6c757d',
              marginBottom: '16px'
            }}>
              or click to browse files
            </div>
            <div style={{
              fontSize: '12px',
              color: '#868e96',
              marginTop: '16px'
            }}>
              Supports JSON trace files up to 200MB
            </div>
          </div>
        )}

        <input
          id="trace-upload"
          type="file"
          accept=".json"
          onChange={handleFileSelect}
          style={{ display: 'none' }}
          disabled={uploading}
        />
      </div>

      {error && (
        <div style={{
          marginTop: '20px',
          padding: '12px 20px',
          backgroundColor: '#f8d7da',
          color: '#721c24',
          border: '1px solid #f5c6cb',
          borderRadius: '8px',
          fontSize: '14px',
          maxWidth: '400px',
          textAlign: 'center'
        }}>
          {error}
        </div>
      )}

      <div style={{
        marginTop: '40px',
        padding: '20px',
        backgroundColor: '#e9ecef',
        borderRadius: '8px',
        maxWidth: '500px'
      }}>
        <h3 style={{ 
          fontSize: '16px', 
          color: '#495057', 
          marginBottom: '12px',
          marginTop: '0'
        }}>
          How to capture a trace:
        </h3>
        <ol style={{ 
          fontSize: '14px', 
          color: '#6c757d', 
          lineHeight: '1.6',
          paddingLeft: '20px',
          margin: '0'
        }}>
          <li>Open Chrome DevTools (F12)</li>
          <li>Go to the Performance tab</li>
          <li>Click the record button and reload your page</li>
          <li>Stop recording and click "Save profile"</li>
          <li>Upload the saved .json file here</li>
        </ol>
      </div>

      <style>{`
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  )
}