'use client'

import { useState, useRef, useEffect } from 'react'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Button } from '@/components/ui/button'
import { 
  CheckSquare, 
  X, 
  Bell, 
  Image, 
  UserPlus, 
  Palette, 
  Archive, 
  MoreVertical,
  Undo2,
  Redo2
} from 'lucide-react'
import { createNote } from '@/app/actions/notes'
import { CheckItem, NOTE_COLORS, NoteColor } from '@/lib/types'
import { Checkbox } from '@/components/ui/checkbox'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { cn } from '@/lib/utils'
import { useToast } from '@/components/ui/toast'

interface NoteState {
  title: string
  content: string
  checkItems: CheckItem[]
  images: string[]
}

export function NoteInput() {
  const { addToast } = useToast()
  const [isExpanded, setIsExpanded] = useState(false)
  const [type, setType] = useState<'text' | 'checklist'>('text')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [color, setColor] = useState<NoteColor>('default')
  const [isArchived, setIsArchived] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  
  // Simple state without complex undo/redo - like Google Keep
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [checkItems, setCheckItems] = useState<CheckItem[]>([])
  const [images, setImages] = useState<string[]>([])

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

    // Validate file types
    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
    const maxSize = 5 * 1024 * 1024 // 5MB

    Array.from(files).forEach(file => {
      // Validation
      if (!validTypes.includes(file.type)) {
        addToast(`Invalid file type: ${file.name}. Only JPEG, PNG, GIF, and WebP allowed.`, 'error')
        return
      }
      
      if (file.size > maxSize) {
        addToast(`File too large: ${file.name}. Maximum size is 5MB.`, 'error')
        return
      }

      const reader = new FileReader()
      reader.onloadend = () => {
        setImages([...images, reader.result as string])
      }
      reader.onerror = () => {
        addToast(`Failed to read file: ${file.name}`, 'error')
      }
      reader.readAsDataURL(file)
    })

    // Reset input
    e.target.value = ''
  }

  const handleReminder = () => {
    const reminderDate = prompt('Enter reminder date and time (e.g., 2026-01-10 14:30):')
    if (!reminderDate) return

    try {
      const date = new Date(reminderDate)
      if (isNaN(date.getTime())) {
        addToast('Invalid date format. Use: YYYY-MM-DD HH:MM', 'error')
        return
      }

      if (date < new Date()) {
        addToast('Reminder date must be in the future', 'error')
        return
      }

      // TODO: Store reminder in database
      addToast(`Reminder set for: ${date.toLocaleString()}`, 'success')
    } catch (error) {
      addToast('Failed to set reminder', 'error')
    }
  }

  const handleSubmit = async () => {
    // Validation
    if (type === 'text' && !content.trim()) {
      addToast('Please enter some content', 'warning')
      return
    }
    if (type === 'checklist' && checkItems.length === 0) {
      addToast('Please add at least one item', 'warning')
      return
    }
    if (type === 'checklist' && checkItems.every(item => !item.text.trim())) {
      addToast('Checklist items cannot be empty', 'warning')
      return
    }

    setIsSubmitting(true)
    try {
      await createNote({
        title: title.trim() || undefined,
        content: type === 'text' ? content : '',
        type,
        checkItems: type === 'checklist' ? checkItems : undefined,
        color,
        isArchived,
        images: images.length > 0 ? images : undefined,
      })

      // Reset form
      setTitle('')
      setContent('')
      setCheckItems([])
      setImages([])
      setIsExpanded(false)
      setType('text')
      setColor('default')
      setIsArchived(false)
      
      addToast('Note created successfully', 'success')
    } catch (error) {
      console.error('Failed to create note:', error)
      addToast('Failed to create note', 'error')
    } finally {
      setIsSubmitting(false)
    }
  }

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

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

  const handleClose = () => {
    setIsExpanded(false)
    setTitle('')
    setContent('')
    setCheckItems([])
    setImages([])
    setType('text')
    setColor('default')
    setIsArchived(false)
  }

  if (!isExpanded) {
    return (
      <Card className="p-4 max-w-2xl mx-auto mb-8 cursor-text shadow-md hover:shadow-lg transition-shadow">
        <div className="flex items-center gap-4">
          <Input
            placeholder="Take a note..."
            onClick={() => setIsExpanded(true)}
            readOnly
            value=""
            className="border-0 focus-visible:ring-0 cursor-text"
          />
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              setType('checklist')
              setIsExpanded(true)
            }}
            title="New checklist"
          >
            <CheckSquare className="h-5 w-5" />
          </Button>
        </div>
      </Card>
    )
  }

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

  return (
    <Card className={cn(
      "p-4 max-w-2xl mx-auto mb-8 shadow-lg border",
      colorClasses.card
    )}>
      <div className="space-y-3">
        <Input
          placeholder="Title"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          className="border-0 focus-visible:ring-0 text-base font-semibold"
        />

        {/* Image Preview */}
        {images.length > 0 && (
          <div className="flex flex-col gap-2">
            {images.map((img, idx) => (
              <div key={idx} className="relative group">
                <img 
                  src={img} 
                  alt={`Upload ${idx + 1}`} 
                  className="max-w-full h-auto max-h-96 object-contain 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={() => setImages(images.filter((_, i) => i !== idx))}
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
            ))}
          </div>
        )}

        {type === 'text' ? (
          <Textarea
            placeholder="Take a note..."
            value={content}
            onChange={(e) => setContent(e.target.value)}
            className="border-0 focus-visible:ring-0 min-h-[100px] resize-none"
            autoFocus
          />
        ) : (
          <div className="space-y-2">
            {checkItems.map((item) => (
              <div key={item.id} className="flex items-start gap-2 group">
                <Checkbox 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"
                  autoFocus={checkItems[checkItems.length - 1].id === item.id}
                />
                <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 w-full justify-start"
            >
              + List item
            </Button>
          </div>
        )}

        <div className="flex items-center justify-between pt-2">
          <TooltipProvider>
            <div className="flex items-center gap-1">
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button 
                    variant="ghost" 
                    size="icon" 
                    className="h-8 w-8" 
                    title="Remind me"
                    onClick={handleReminder}
                  >
                    <Bell className="h-4 w-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>Remind me</TooltipContent>
              </Tooltip>

              <Tooltip>
                <TooltipTrigger asChild>
                  <Button 
                    variant="ghost" 
                    size="icon" 
                    className="h-8 w-8" 
                    title="Add image"
                    onClick={() => fileInputRef.current?.click()}
                  >
                    <Image className="h-4 w-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>Add image</TooltipContent>
              </Tooltip>

              <Tooltip>
                <TooltipTrigger asChild>
                  <Button variant="ghost" size="icon" className="h-8 w-8" title="Collaborator">
                    <UserPlus className="h-4 w-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>Collaborator</TooltipContent>
              </Tooltip>

              <DropdownMenu>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="h-8 w-8" title="Background options">
                        <Palette className="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                  </TooltipTrigger>
                  <TooltipContent>Background options</TooltipContent>
                </Tooltip>
                <DropdownMenuContent align="start" className="w-40">
                  <div className="grid grid-cols-5 gap-2 p-2">
                    {Object.entries(NOTE_COLORS).map(([colorName, colorClass]) => (
                      <button
                        key={colorName}
                        onClick={() => setColor(colorName as NoteColor)}
                        className={cn(
                          'w-7 h-7 rounded-full border-2 hover:scale-110 transition-transform',
                          colorClass.bg,
                          color === colorName ? 'border-gray-900 dark:border-gray-100' : 'border-transparent'
                        )}
                        title={colorName}
                      />
                    ))}
                  </div>
                </DropdownMenuContent>
              </DropdownMenu>

              <Tooltip>
                <TooltipTrigger asChild>
                  <Button 
                    variant="ghost" 
                    size="icon" 
                    className={cn(
                      "h-8 w-8",
                      isArchived && "text-yellow-600"
                    )}
                    onClick={() => setIsArchived(!isArchived)}
                    title="Archive"
                  >
                    <Archive className="h-4 w-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>{isArchived ? 'Unarchive' : 'Archive'}</TooltipContent>
              </Tooltip>

              <Tooltip>
                <TooltipTrigger asChild>
                  <Button variant="ghost" size="icon" className="h-8 w-8" title="More">
                    <MoreVertical className="h-4 w-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>More</TooltipContent>
              </Tooltip>
            </TooltipProvider>

            <div className="flex gap-2">
              <Button
                onClick={handleSubmit}
                disabled={isSubmitting}
                size="sm"
            </TooltipProvider>

            <div className="flex gap-2">
              <Button
                onClick={handleSubmit}
                disabled={isSubmitting}
                size="sm"
              >
                {isSubmitting ? 'Adding...' : 'Add'}
              </Button>
              <Button 
                variant="ghost" 
                onClick={handleClose}
                size="sm"
              >
                Close
              </Button>
            </div>
          </div>
        </div>
      </div>
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        multiple
        className="hidden"
        onChange={handleImageUpload}
      />
    </Card>
  )
}
