'use client'

import { useState, useEffect, useRef } from 'react'
import { Note, CheckItem, NOTE_COLORS, NoteColor } from '@/lib/types'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { X, Plus, Palette, Image as ImageIcon, Bell, FileText, Eye } from 'lucide-react'
import { updateNote } from '@/app/actions/notes'
import { cn } from '@/lib/utils'
import { useToast } from '@/components/ui/toast'
import { MarkdownContent } from './markdown-content'
import { LabelManager } from './label-manager'
import { LabelBadge } from './label-badge'

interface NoteEditorProps {
  note: Note
  onClose: () => void
}

export function NoteEditor({ note, onClose }: NoteEditorProps) {
  const { addToast } = useToast()
  const [title, setTitle] = useState(note.title || '')
  const [content, setContent] = useState(note.content)
  const [checkItems, setCheckItems] = useState<CheckItem[]>(note.checkItems || [])
  const [labels, setLabels] = useState<string[]>(note.labels || [])
  const [images, setImages] = useState<string[]>(note.images || [])
  const [newLabel, setNewLabel] = useState('')
  const [color, setColor] = useState(note.color)
  const [isSaving, setIsSaving] = useState(false)
  const [isMarkdown, setIsMarkdown] = useState(note.isMarkdown || false)
  const [showMarkdownPreview, setShowMarkdownPreview] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  
  // Reminder state
  const [showReminderDialog, setShowReminderDialog] = useState(false)
  const [reminderDate, setReminderDate] = useState('')
  const [reminderTime, setReminderTime] = useState('')
  const [currentReminder, setCurrentReminder] = useState<Date | null>(note.reminder)

  const colorClasses = NOTE_COLORS[color as NoteColor] || NOTE_COLORS.default

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files
    if (!files) return

    Array.from(files).forEach(file => {
      const reader = new FileReader()
      reader.onloadend = () => {
        setImages(prev => [...prev, reader.result as string])
      }
      reader.readAsDataURL(file)
    })
  }

  const handleRemoveImage = (index: number) => {
    setImages(images.filter((_, i) => i !== index))
  }

  const handleReminderOpen = () => {
    if (currentReminder) {
      const date = new Date(currentReminder)
      setReminderDate(date.toISOString().split('T')[0])
      setReminderTime(date.toTimeString().slice(0, 5))
    } else {
      const tomorrow = new Date(Date.now() + 86400000)
      setReminderDate(tomorrow.toISOString().split('T')[0])
      setReminderTime('09:00')
    }
    setShowReminderDialog(true)
  }
  
  const handleReminderSave = () => {
    if (!reminderDate || !reminderTime) {
      addToast('Please enter date and time', 'warning')
      return
    }
    
    const dateTimeString = `${reminderDate}T${reminderTime}`
    const date = new Date(dateTimeString)
    
    if (isNaN(date.getTime())) {
      addToast('Invalid date or time', 'error')
      return
    }
    
    if (date < new Date()) {
      addToast('Reminder must be in the future', 'error')
      return
    }
    
    setCurrentReminder(date)
    addToast(`Reminder set for ${date.toLocaleString()}`, 'success')
    setShowReminderDialog(false)
  }
  
  const handleRemoveReminder = () => {
    setCurrentReminder(null)
    setShowReminderDialog(false)
    addToast('Reminder removed', 'success')
  }

  const handleSave = async () => {
    setIsSaving(true)
    try {
      await updateNote(note.id, {
        title: title.trim() || null,
        content: note.type === 'text' ? content : '',
        checkItems: note.type === 'checklist' ? checkItems : null,
        labels,
        images,
        color,
        reminder: currentReminder,
        isMarkdown,
      })
      onClose()
    } catch (error) {
      console.error('Failed to save note:', error)
    } finally {
      setIsSaving(false)
    }
  }

  const handleCheckItem = (id: string) => {
    setCheckItems(items =>
      items.map(item =>
        item.id === id ? { ...item, checked: !item.checked } : item
      )
    )
  }

  const handleUpdateCheckItem = (id: string, text: string) => {
    setCheckItems(items =>
      items.map(item => (item.id === id ? { ...item, text } : item))
    )
  }

  const handleAddCheckItem = () => {
    setCheckItems([
      ...checkItems,
      { id: Date.now().toString(), text: '', checked: false },
    ])
  }

  const handleRemoveCheckItem = (id: string) => {
    setCheckItems(items => items.filter(item => item.id !== id))
  }

  const handleAddLabel = () => {
    if (newLabel.trim() && !labels.includes(newLabel.trim())) {
      setLabels([...labels, newLabel.trim()])
      setNewLabel('')
    }
  }

  const handleRemoveLabel = (label: string) => {
    setLabels(labels.filter(l => l !== label))
  }

  return (
    <Dialog open onOpenChange={onClose}>
      <DialogContent
        className={cn(
          '!max-w-[min(95vw,1600px)] max-h-[90vh] overflow-y-auto',
          colorClasses.bg
        )}
      >
        <DialogHeader>
          <DialogTitle className="sr-only">Edit Note</DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* Title */}
          <Input
            placeholder="Title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            className="text-lg font-semibold border-0 focus-visible:ring-0 px-0 bg-transparent"
          />

          {/* Images */}
          {images.length > 0 && (
            <div className="flex flex-col gap-3 mb-4">
              {images.map((img, idx) => (
                <div key={idx} className="relative group">
                  <img 
                    src={img} 
                    alt="" 
                    className="h-auto rounded-lg"
                  />
                  <Button
                    variant="ghost"
                    size="sm"
                    className="absolute top-2 right-2 h-7 w-7 p-0 bg-white/90 hover:bg-white opacity-0 group-hover:opacity-100 transition-opacity"
                    onClick={() => handleRemoveImage(idx)}
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          )}

          {/* Content or Checklist */}
          {note.type === 'text' ? (
            <div className="space-y-2">
              {/* Markdown controls */}
              <div className="flex items-center justify-between gap-2 pb-2">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    setIsMarkdown(!isMarkdown)
                    if (isMarkdown) setShowMarkdownPreview(false)
                  }}
                  className={cn("h-7 text-xs", isMarkdown && "text-blue-600")}
                >
                  <FileText className="h-3 w-3 mr-1" />
                  {isMarkdown ? 'Markdown ON' : 'Markdown OFF'}
                </Button>
                
                {isMarkdown && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setShowMarkdownPreview(!showMarkdownPreview)}
                    className="h-7 text-xs"
                  >
                    {showMarkdownPreview ? (
                      <>
                        <FileText className="h-3 w-3 mr-1" />
                        Edit
                      </>
                    ) : (
                      <>
                        <Eye className="h-3 w-3 mr-1" />
                        Preview
                      </>
                    )}
                  </Button>
                )}
              </div>

              {showMarkdownPreview && isMarkdown ? (
                <MarkdownContent 
                  content={content || '*No content*'} 
                  className="min-h-[200px] p-3 rounded-md border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50"
                />
              ) : (
                <Textarea
                  placeholder={isMarkdown ? "Take a note... (Markdown supported)" : "Take a note..."}
                  value={content}
                  onChange={(e) => setContent(e.target.value)}
                  className="min-h-[200px] border-0 focus-visible:ring-0 px-0 bg-transparent resize-none"
                />
              )}
            </div>
          ) : (
            <div className="space-y-2">
              {checkItems.map((item) => (
                <div key={item.id} className="flex items-start gap-2 group">
                  <Checkbox
                    checked={item.checked}
                    onCheckedChange={() => handleCheckItem(item.id)}
                    className="mt-2"
                  />
                  <Input
                    value={item.text}
                    onChange={(e) => handleUpdateCheckItem(item.id, e.target.value)}
                    placeholder="List item"
                    className="flex-1 border-0 focus-visible:ring-0 px-0 bg-transparent"
                  />
                  <Button
                    variant="ghost"
                    size="sm"
                    className="opacity-0 group-hover:opacity-100 h-8 w-8 p-0"
                    onClick={() => handleRemoveCheckItem(item.id)}
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              ))}
              <Button
                variant="ghost"
                size="sm"
                onClick={handleAddCheckItem}
                className="text-gray-600 dark:text-gray-400"
              >
                <Plus className="h-4 w-4 mr-1" />
                Add item
              </Button>
            </div>
          )}

          {/* Labels */}
          {labels.length > 0 && (
            <div className="flex flex-wrap gap-2">
              {labels.map((label) => (
                <LabelBadge
                  key={label}
                  label={label}
                  onRemove={() => handleRemoveLabel(label)}
                />
              ))}
            </div>
          )}

          {/* Toolbar */}
          <div className="flex items-center justify-between pt-4 border-t">
            <div className="flex items-center gap-2">
              {/* Reminder Button */}
              <Button 
                variant="ghost" 
                size="sm" 
                onClick={handleReminderOpen}
                title="Set reminder"
                className={currentReminder ? "text-blue-600" : ""}
              >
                <Bell className="h-4 w-4" />
              </Button>

              {/* Add Image Button */}
              <Button 
                variant="ghost" 
                size="sm" 
                onClick={() => fileInputRef.current?.click()}
                title="Add image"
              >
                <ImageIcon className="h-4 w-4" />
              </Button>

              {/* Color Picker */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="sm" title="Change color">
                    <Palette className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent>
                  <div className="grid grid-cols-5 gap-2 p-2">
                    {Object.entries(NOTE_COLORS).map(([colorName, classes]) => (
                      <button
                        key={colorName}
                        className={cn(
                          'h-8 w-8 rounded-full border-2 transition-transform hover:scale-110',
                          classes.bg,
                          color === colorName ? 'border-gray-900 dark:border-gray-100' : 'border-gray-300 dark:border-gray-700'
                        )}
                        onClick={() => setColor(colorName)}
                        title={colorName}
                      />
                    ))}
                  </div>
                </DropdownMenuContent>
              </DropdownMenu>

              {/* Label Manager */}
              <LabelManager
                existingLabels={labels}
                onUpdate={setLabels}
              />
            </div>

            <div className="flex gap-2">
              <Button variant="ghost" onClick={onClose}>
                Cancel
              </Button>
              <Button onClick={handleSave} disabled={isSaving}>
                {isSaving ? 'Saving...' : 'Save'}
              </Button>
            </div>
          </div>
        </div>
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          multiple
          className="hidden"
          onChange={handleImageUpload}
        />
      </DialogContent>

      {/* Reminder Dialog */}
      <Dialog open={showReminderDialog} onOpenChange={setShowReminderDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Set Reminder</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <label htmlFor="reminder-date" className="text-sm font-medium">
                Date
              </label>
              <Input
                id="reminder-date"
                type="date"
                value={reminderDate}
                onChange={(e) => setReminderDate(e.target.value)}
                className="w-full"
              />
            </div>
            <div className="space-y-2">
              <label htmlFor="reminder-time" className="text-sm font-medium">
                Time
              </label>
              <Input
                id="reminder-time"
                type="time"
                value={reminderTime}
                onChange={(e) => setReminderTime(e.target.value)}
                className="w-full"
              />
            </div>
          </div>
          <div className="flex justify-between">
            <div>
              {currentReminder && (
                <Button variant="outline" onClick={handleRemoveReminder}>
                  Remove Reminder
                </Button>
              )}
            </div>
            <div className="flex gap-2">
              <Button variant="ghost" onClick={() => setShowReminderDialog(false)}>
                Cancel
              </Button>
              <Button onClick={handleReminderSave}>
                Set Reminder
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </Dialog>
  )
}
