"use client"

import React, { useState } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog'
import { Button } from '../ui/button'
import { Input } from '../ui/input'
import { Textarea } from '../ui/textarea'
import { Label } from '../ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select'
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from '../ui/command'
import { Calendar as CalendarComponent } from '../ui/calendar'
import { MoonUIAvatarPro, MoonUIAvatarFallbackPro, MoonUIAvatarImagePro, AvatarGroup as MoonUIAvatarGroupPro } from '../ui/avatar'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs'
import { Badge } from '../ui/badge'
import { 
  Calendar, 
  User, 
  Tag, 
  Flag,
  Check,
  ChevronDown,
  FileText,
  Star,
  Zap,
  Clock,
  CheckSquare
} from 'lucide-react'
import { format } from 'date-fns'
import { cn } from '../../lib/utils'
import type { KanbanCard, KanbanAssignee, KanbanLabel } from './types'

interface AddCardModalProps {
  isOpen: boolean
  onClose: () => void
  onAdd: (card: Partial<KanbanCard>) => void
  columnId: string
  columnTitle: string
  availableAssignees?: KanbanAssignee[]
  availableLabels?: KanbanLabel[]
  templates?: Partial<KanbanCard>[]
}

const PRIORITY_OPTIONS = [
  { value: 'low', label: 'Low Priority', icon: Flag, color: 'text-green-600' },
  { value: 'medium', label: 'Medium Priority', icon: Flag, color: 'text-yellow-600' },
  { value: 'high', label: 'High Priority', icon: Flag, color: 'text-orange-600' },
  { value: 'urgent', label: 'Urgent', icon: Zap, color: 'text-red-600' }
]

const CARD_TEMPLATES = [
  {
    name: 'Bug Report',
    icon: Flag,
    template: {
      title: 'Bug: ',
      description: '**Steps to Reproduce:**\n1. \n2. \n3. \n\n**Expected Behavior:**\n\n**Actual Behavior:**',
      priority: 'high' as const,
      tags: ['bug']
    }
  },
  {
    name: 'Feature Request',
    icon: Star,
    template: {
      title: 'Feature: ',
      description: '**User Story:**\nAs a [user type], I want [feature] so that [benefit].\n\n**Acceptance Criteria:**\n- [ ] ',
      priority: 'medium' as const,
      tags: ['feature']
    }
  },
  {
    name: 'Task',
    icon: CheckSquare,
    template: {
      title: 'Task: ',
      description: '**Objective:**\n\n**Tasks:**\n- [ ] ',
      priority: 'medium' as const,
      tags: ['task']
    }
  },
  {
    name: 'User Story',
    icon: User,
    template: {
      title: 'As a ',
      description: '**Story:**\nAs a [user type]\nI want [functionality]\nSo that [benefit]\n\n**Acceptance Criteria:**\n- [ ] ',
      priority: 'medium' as const,
      tags: ['story']
    }
  }
]

const getInitials = (name: string) => {
  return name.split(' ').map(n => n[0]).join('').toUpperCase()
}

export function AddCardModal({
  isOpen,
  onClose,
  onAdd,
  columnId,
  columnTitle,
  availableAssignees = [],
  availableLabels = [],
  templates = []
}: AddCardModalProps) {
  const [selectedTab, setSelectedTab] = useState('blank')
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [priority, setPriority] = useState<'low' | 'medium' | 'high' | 'urgent'>('medium')
  const [assignees, setAssignees] = useState<KanbanAssignee[]>([])
  const [labels, setLabels] = useState<KanbanLabel[]>([])
  const [dueDate, setDueDate] = useState<Date | undefined>()
  const [tags, setTags] = useState<string[]>([])
  const [tagInput, setTagInput] = useState('')

  const handleTemplateSelect = (template: Partial<KanbanCard>) => {
    setTitle(template.title || '')
    setDescription(template.description || '')
    setPriority(template.priority || 'medium')
    setTags(template.tags || [])
    if (template.assignees) setAssignees(template.assignees)
    if (template.labels) setLabels(template.labels)
    if (template.dueDate) setDueDate(template.dueDate)
  }

  const handleSubmit = () => {
    if (!title.trim()) return

    const newCard: Partial<KanbanCard> = {
      title: title.trim(),
      description: description.trim() || undefined,
      priority,
      assignees: assignees.length > 0 ? assignees : undefined,
      labels: labels.length > 0 ? labels : undefined,
      dueDate,
      tags: tags.length > 0 ? tags : undefined,
      position: Date.now()
    }

    onAdd(newCard)
    resetForm()
    onClose()
  }

  const resetForm = () => {
    setTitle('')
    setDescription('')
    setPriority('medium')
    setAssignees([])
    setLabels([])
    setDueDate(undefined)
    setTags([])
    setTagInput('')
    setSelectedTab('blank')
  }

  const handleAddTag = () => {
    if (tagInput.trim() && !tags.includes(tagInput.trim())) {
      setTags([...tags, tagInput.trim()])
      setTagInput('')
    }
  }

  const allTemplates = [...CARD_TEMPLATES.map(t => ({ ...t.template, name: t.name, icon: t.icon })), ...templates]

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>Add Card to {columnTitle}</DialogTitle>
        </DialogHeader>

        <Tabs value={selectedTab} onValueChange={setSelectedTab}>
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="blank">Blank Card</TabsTrigger>
            <TabsTrigger value="template">From Template</TabsTrigger>
          </TabsList>

          <TabsContent value="blank" className="space-y-4">
            <div className="space-y-4">
              {/* Title */}
              <div>
                <Label htmlFor="title">Title *</Label>
                <Input
                  id="title"
                  placeholder="Enter card title..."
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  autoFocus
                />
              </div>

              {/* Description */}
              <div>
                <Label htmlFor="description">Description</Label>
                <Textarea
                  id="description"
                  placeholder="Add a more detailed description..."
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  className="min-h-[100px]"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                {/* Priority */}
                <div>
                  <Label>Priority</Label>
                  <Select value={priority} onValueChange={(value: any) => setPriority(value)}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {PRIORITY_OPTIONS.map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          <div className="flex items-center gap-2">
                            <option.icon className={cn("h-4 w-4", option.color)} />
                            <span>{option.label}</span>
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {/* Due Date */}
                <div>
                  <Label>Due Date</Label>
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button variant="outline" className="w-full justify-start">
                        {dueDate ? (
                          <>
                            <Calendar className="mr-2 h-4 w-4" />
                            {format(dueDate, 'PPP')}
                          </>
                        ) : (
                          <>
                            <Calendar className="mr-2 h-4 w-4" />
                            <span className="text-muted-foreground">Pick a date</span>
                          </>
                        )}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto p-0" align="start">
                      <CalendarComponent
                        mode="single"
                        selected={dueDate}
                        onSelect={(date) => {
                          if (date instanceof Date) {
                            setDueDate(date)
                          } else {
                            setDueDate(undefined)
                          }
                        }}
                        initialFocus
                      />
                    </PopoverContent>
                  </Popover>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                {/* Assignees */}
                <div>
                  <Label>Assignees</Label>
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button variant="outline" className="w-full justify-start">
                        {assignees.length > 0 ? (
                          <div className="flex items-center gap-2">
                            <MoonUIAvatarGroupPro max={2} size="xs">
                              {assignees.map((assignee) => (
                                <MoonUIAvatarPro key={assignee.id} className="h-5 w-5">
                                  <MoonUIAvatarImagePro src={assignee.avatar} />
                                  <MoonUIAvatarFallbackPro className="text-xs">
                                    {getInitials(assignee.name)}
                                  </MoonUIAvatarFallbackPro>
                                </MoonUIAvatarPro>
                              ))}
                            </MoonUIAvatarGroupPro>
                            <span className="text-sm truncate">
                              {assignees.map(a => a.name).join(', ')}
                            </span>
                          </div>
                        ) : (
                          <>
                            <User className="mr-2 h-4 w-4" />
                            <span className="text-muted-foreground">Select assignees</span>
                          </>
                        )}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="p-0" align="start">
                      <Command>
                        <CommandInput placeholder="Search people..." />
                        <CommandEmpty>No assignees found.</CommandEmpty>
                        <CommandGroup>
                          {availableAssignees.map((assignee) => {
                            const isSelected = assignees.some(a => a.id === assignee.id)
                            return (
                              <CommandItem
                                key={assignee.id}
                                onSelect={() => {
                                  if (isSelected) {
                                    setAssignees(assignees.filter(a => a.id !== assignee.id))
                                  } else {
                                    setAssignees([...assignees, assignee])
                                  }
                                }}
                              >
                                <Check
                                  className={cn(
                                    "mr-2 h-4 w-4",
                                    isSelected ? "opacity-100" : "opacity-0"
                                  )}
                                />
                                <MoonUIAvatarPro className="h-6 w-6 mr-2">
                                  <MoonUIAvatarImagePro src={assignee.avatar} />
                                  <MoonUIAvatarFallbackPro className="text-xs">
                                    {getInitials(assignee.name)}
                                  </MoonUIAvatarFallbackPro>
                                </MoonUIAvatarPro>
                                <span>{assignee.name}</span>
                              </CommandItem>
                            )
                          })}
                        </CommandGroup>
                      </Command>
                    </PopoverContent>
                  </Popover>
                </div>

                {/* Labels */}
                <div>
                  <Label>Labels</Label>
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button variant="outline" className="w-full justify-start">
                        {labels.length > 0 ? (
                          <div className="flex items-center gap-1 truncate">
                            {labels.slice(0, 2).map((label) => (
                              <div
                                key={label.id}
                                className="px-2 py-0.5 rounded text-xs text-white"
                                style={{ backgroundColor: label.color }}
                              >
                                {label.name}
                              </div>
                            ))}
                            {labels.length > 2 && (
                              <span className="text-sm text-muted-foreground">
                                +{labels.length - 2} more
                              </span>
                            )}
                          </div>
                        ) : (
                          <>
                            <Tag className="mr-2 h-4 w-4" />
                            <span className="text-muted-foreground">Select labels</span>
                          </>
                        )}
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="p-3" align="start">
                      <div className="space-y-2">
                        {availableLabels.map((label) => {
                          const isSelected = labels.some(l => l.id === label.id)
                          return (
                            <div
                              key={label.id}
                              className={cn(
                                "flex items-center gap-2 p-2 rounded cursor-pointer hover:bg-muted",
                                isSelected && "bg-muted"
                              )}
                              onClick={() => {
                                if (isSelected) {
                                  setLabels(labels.filter(l => l.id !== label.id))
                                } else {
                                  setLabels([...labels, label])
                                }
                              }}
                            >
                              <div
                                className="w-6 h-6 rounded"
                                style={{ backgroundColor: label.color }}
                              />
                              <span className="text-sm">{label.name}</span>
                              {isSelected && <Check className="h-4 w-4 ml-auto" />}
                            </div>
                          )
                        })}
                      </div>
                    </PopoverContent>
                  </Popover>
                </div>
              </div>

              {/* Tags */}
              <div>
                <Label>Tags</Label>
                <div className="space-y-2">
                  <div className="flex gap-2">
                    <Input
                      placeholder="Add a tag..."
                      value={tagInput}
                      onChange={(e) => setTagInput(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') {
                          e.preventDefault()
                          handleAddTag()
                        }
                      }}
                    />
                    <Button
                      type="button"
                      variant="outline"
                      onClick={handleAddTag}
                      disabled={!tagInput.trim()}
                    >
                      Add
                    </Button>
                  </div>
                  {tags.length > 0 && (
                    <div className="flex flex-wrap gap-2">
                      {tags.map((tag) => (
                        <Badge
                          key={tag}
                          variant="secondary"
                          className="cursor-pointer"
                          onClick={() => setTags(tags.filter(t => t !== tag))}
                        >
                          {tag}
                          <span className="ml-1 hover:text-destructive">×</span>
                        </Badge>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </TabsContent>

          <TabsContent value="template" className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              {CARD_TEMPLATES.map((template) => (
                <div
                  key={template.name}
                  className="p-4 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors"
                  onClick={() => {
                    handleTemplateSelect(template.template)
                    setSelectedTab('blank')
                  }}
                >
                  <div className="flex items-center gap-3 mb-2">
                    <template.icon className="h-5 w-5 text-muted-foreground" />
                    <h4 className="font-medium">{template.name}</h4>
                  </div>
                  <p className="text-sm text-muted-foreground">
                    {template.name === 'Bug Report' && 'Track and fix bugs with detailed information'}
                    {template.name === 'Feature Request' && 'Plan new features with user stories'}
                    {template.name === 'Task' && 'Create actionable tasks with clear objectives'}
                    {template.name === 'User Story' && 'Define user needs and acceptance criteria'}
                  </p>
                </div>
              ))}
              {templates.map((template, index) => (
                <div
                  key={`custom-${index}`}
                  className="p-4 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors"
                  onClick={() => {
                    handleTemplateSelect(template)
                    setSelectedTab('blank')
                  }}
                >
                  <div className="flex items-center gap-3 mb-2">
                    <Star className="h-5 w-5 text-muted-foreground" />
                    <h4 className="font-medium">{template.title || `Template ${index + 1}`}</h4>
                  </div>
                  <p className="text-sm text-muted-foreground line-clamp-2">
                    {template.description || 'Custom template'}
                  </p>
                </div>
              ))}
            </div>
          </TabsContent>
        </Tabs>

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button onClick={handleSubmit} disabled={!title.trim()}>
            Add Card
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}