import React, { useCallback, useEffect, useState } from 'react'
import { Box, Paper, TextField, Typography, Alert } from '@mui/material'
import { useDropzone } from 'react-dropzone'
import { useTracklistStore } from '../stores/tracklistStore'
import { validateTracklist, parseTracklist } from '../utils/validators'
import { TracklistEntry } from '../types'

export const TracklistEditor: React.FC = () => {
  const { rawText, errors, isValid, setRawText, setEntries, setErrors, setIsValid } = useTracklistStore()
  const [isDragging, setIsDragging] = useState(false)

  const handleTextChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    const text = event.target.value
    setRawText(text)
    validate(text)
  }

  const validate = (text: string) => {
    const lines = text.split('\n').filter((line) => line.trim() !== '')
    const parsed = parseTracklist(lines)
    setEntries(parsed)

    const validation = validateTracklist(parsed)
    setErrors(validation.errors)
    setIsValid(validation.isValid)
  }

  const onDrop = useCallback(
    (acceptedFiles: File[]) => {
      if (acceptedFiles.length === 0) return

      const file = acceptedFiles[0]
      const reader = new FileReader()
      reader.onload = (event) => {
        const text = event.target?.result as string
        setRawText(text)
        validate(text)
        setIsDragging(false)
      }
      reader.readAsText(file)
    },
    [setRawText]
  )

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'text/plain': ['.txt'],
    },
    multiple: false,
  })

  // Initial validation on mount
  useEffect(() => {
    if (rawText) {
      validate(rawText)
    }
  }, [])

  const getLineClassName = (lineIndex: number): string => {
    const hasError = errors.some((e) => e.line === lineIndex + 1)
    return hasError ? 'error-line' : ''
  }

  return (
    <Paper
      {...getRootProps()}
      sx={{
        p: 3,
        border: isDragActive ? '2px dashed' : '1px solid',
        borderColor: isDragActive ? 'primary.main' : 'divider',
        borderRadius: 2,
        backgroundColor: isDragActive ? 'action.hover' : 'background.paper',
        transition: 'all 0.2s ease',
      }}
    >
      <input {...getInputProps()} />

      <Typography variant="subtitle1" sx={{ mb: 2 }}>
        Tracklist
        <Typography variant="caption" color="text.secondary" sx={{ ml: 2 }}>
          {rawText ? `${rawText.split('\n').filter((l) => l.trim()).length} tracks` : 'No tracks yet'}
          {isValid ? ' ✅' : errors.length > 0 ? ` ⚠️ ${errors.length} error(s)` : ''}
        </Typography>
      </Typography>

      <Box sx={{ display: 'flex', gap: 2 }}>
        {/* Line numbers column */}
        <Box
          sx={{
            minWidth: 40,
            maxWidth: 40,
            fontFamily: 'monospace',
            fontSize: '14px',
            lineHeight: 1.7,
            color: 'text.secondary',
            textAlign: 'right',
            userSelect: 'none',
            overflow: 'hidden',
          }}
        >
          {rawText.split('\n').map((_, i) => (
            <div key={i}>{i + 1}</div>
          ))}
        </Box>

        {/* Editor text area */}
        <TextField
          multiline
          fullWidth
          minRows={10}
          maxRows={20}
          value={rawText}
          onChange={handleTextChange}
          placeholder={`Enter your tracklist here...\n\nExample:\n00:00 Intro\n01:30 Song One - Artist A\n04:20-06:45 Another Song - Artist B`}
          variant="outlined"
          sx={{
            '& .MuiInputBase-root': {
              fontFamily: 'monospace',
              fontSize: '14px',
              lineHeight: 1.7,
            },
          }}
          error={!isValid && errors.length > 0}
          helperText={
            !isValid && errors.length > 0
              ? errors.map((e) => `Line ${e.line}: ${e.message}`).join('; ')
              : 'Drop a .txt file here or paste your tracklist'
          }
        />
      </Box>

      {isDragActive && (
        <Alert severity="info" sx={{ mt: 2 }}>
          Drop your tracklist file (.txt) here
        </Alert>
      )}
    </Paper>
  )
}