'use client'

import { useCallback, useMemo } from 'react'
import { CheckCircle, Circle, Trash, Plus, WarningCircle } from '@phosphor-icons/react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'

export interface KeyValueItem {
  id: string
  key: string
  value: string
  active: boolean
  description?: string
}

interface KeyValueEditorProps {
  items: KeyValueItem[]
  onChange: (items: KeyValueItem[]) => void
  title?: string
  keyLabel?: string
  valueLabel?: string
  showDescription?: boolean
  readOnly?: boolean
  /** Show error styling to indicate this section needs attention */
  showError?: boolean
}

let idCounter = 0
const generateId = () => `kv_${Date.now()}_${idCounter++}`

export function KeyValueEditor({
  items,
  onChange,
  title = 'Parameters',
  keyLabel = 'Name',
  valueLabel = 'Value',
  showDescription = false,
  readOnly = false,
  showError = false,
}: KeyValueEditorProps) {
  // Ensure there's always an empty row at the end for new entries
  const workingItems = useMemo(() => {
    if (items.length === 0 || items[items.length - 1].key !== '') {
      return [...items, { id: generateId(), key: '', value: '', active: true, description: '' }]
    }
    return items
  }, [items])

  const updateItem = useCallback((index: number, updates: Partial<KeyValueItem>) => {
    const newItems = workingItems.map((item, i) => 
      i === index ? { ...item, ...updates } : item
    )
    const filtered = newItems.filter((item, i) => 
      i === newItems.length - 1 || item.key !== '' || item.value !== ''
    )
    onChange(filtered.filter(item => item.key !== '' || item.value !== ''))
  }, [workingItems, onChange])

  const deleteItem = useCallback((index: number) => {
    const newItems = workingItems.filter((_, i) => i !== index)
    onChange(newItems.filter(item => item.key !== ''))
  }, [workingItems, onChange])

  const addItem = useCallback(() => {
    onChange([...items, { id: generateId(), key: '', value: '', active: true, description: '' }])
  }, [items, onChange])

  const clearAll = useCallback(() => {
    onChange([])
  }, [onChange])

  const toggleActive = useCallback((index: number) => {
    const item = workingItems[index]
    if (item) {
      updateItem(index, { active: !item.active })
    }
  }, [workingItems, updateItem])

  const activeCount = useMemo(() => {
    return items.filter(item => item.active && item.key).length
  }, [items])

  const hasItems = items.some(item => item.key !== '')

  return (
    <TooltipProvider>
      <div className="flex flex-1 flex-col h-full">
        {/* Header */}
        <div className={cn(
          "sticky top-0 z-10 flex items-center justify-between border-b bg-muted/30 px-4 py-2",
          showError ? "border-red-500 bg-red-500/5" : "border-border"
        )}>
          <div className="flex items-center gap-2">
            {showError && (
              <WarningCircle className="h-4 w-4 text-red-500 animate-pulse" weight="fill" />
            )}
            <label className={cn(
              "truncate font-semibold text-sm",
              showError ? "text-red-500" : "text-foreground"
            )}>
              {title}
            </label>
            {activeCount > 0 && (
              <span className="text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded-full">
                {activeCount}
              </span>
            )}
          </div>
          <div className="flex items-center gap-1">
            {hasItems && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-7 w-7 text-muted-foreground hover:text-destructive"
                    onClick={clearAll}
                    disabled={readOnly}
                  >
                    <Trash className="h-3.5 w-3.5" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>Clear all</TooltipContent>
              </Tooltip>
            )}
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-7 w-7 text-muted-foreground hover:text-foreground"
                  onClick={addItem}
                  disabled={readOnly}
                >
                  <Plus className="h-3.5 w-3.5" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Add new</TooltipContent>
            </Tooltip>
          </div>
        </div>

        {/* Items */}
        <div className="flex-1 overflow-auto">
          {workingItems.length > 0 && (
            <table className="w-full text-sm">
              <thead className="text-xs text-muted-foreground sticky top-0 z-10">
                <tr className="bg-background border-b border-border/40 shadow-sm">
                  <th className="text-left font-medium px-3 py-2.5 w-[45%] bg-background">{keyLabel}</th>
                  <th className="text-left font-medium px-3 py-2.5 w-[45%] bg-background">{valueLabel}</th>
                  {showDescription && (
                    <th className="text-left font-medium px-3 py-2.5 bg-background">Description</th>
                  )}
                  <th className="w-16 bg-background"></th>
                </tr>
              </thead>
              <tbody>
                {workingItems.map((item, index) => {
                  const isLastEmpty = index === workingItems.length - 1 && !item.key
                  return (
                    <tr 
                      key={item.id} 
                      className={`border-b border-border/50 hover:bg-muted/20 group ${!item.active ? 'opacity-50' : ''}`}
                    >
                      <td className="px-2 py-1.5">
                        <Input
                          type="text"
                          value={item.key}
                          onChange={(e) => updateItem(index, { key: e.target.value })}
                          placeholder={isLastEmpty ? `Add ${keyLabel.toLowerCase()}...` : ''}
                          className="h-9 bg-background border border-border/60 focus-visible:ring-1 focus-visible:ring-primary/30 focus-visible:border-primary/50 placeholder:text-muted-foreground/50"
                          disabled={readOnly}
                        />
                      </td>
                      <td className="px-2 py-1.5">
                        <Input
                          type="text"
                          value={item.value}
                          onChange={(e) => updateItem(index, { value: e.target.value })}
                          placeholder={isLastEmpty ? `Add ${valueLabel.toLowerCase()}...` : ''}
                          className="h-9 bg-background border border-border/60 focus-visible:ring-1 focus-visible:ring-primary/30 focus-visible:border-primary/50 placeholder:text-muted-foreground/50"
                          disabled={readOnly}
                        />
                      </td>
                      {showDescription && (
                        <td className="px-2 py-1.5">
                          <Input
                            type="text"
                            value={item.description || ''}
                            onChange={(e) => updateItem(index, { description: e.target.value })}
                            placeholder=""
                            className="h-9 bg-background border border-border/60 focus-visible:ring-1 focus-visible:ring-primary/30 focus-visible:border-primary/50 text-muted-foreground"
                            disabled={readOnly}
                          />
                        </td>
                      )}
                      <td className="px-2 py-1.5">
                        <div className="flex items-center justify-end gap-0.5">
                          {!isLastEmpty && (
                            <>
                              <Tooltip>
                                <TooltipTrigger asChild>
                                  <Button
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7"
                                    onClick={() => toggleActive(index)}
                                    disabled={readOnly}
                                  >
                                    {item.active ? (
                                      <CheckCircle className="h-4 w-4 text-green-500" weight="fill" />
                                    ) : (
                                      <Circle className="h-4 w-4 text-muted-foreground" />
                                    )}
                                  </Button>
                                </TooltipTrigger>
                                <TooltipContent>{item.active ? 'Disable' : 'Enable'}</TooltipContent>
                              </Tooltip>
                              <Tooltip>
                                <TooltipTrigger asChild>
                                  <Button
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7 text-muted-foreground hover:text-destructive"
                                    onClick={() => deleteItem(index)}
                                    disabled={readOnly}
                                  >
                                    <Trash className="h-3.5 w-3.5" />
                                  </Button>
                                </TooltipTrigger>
                                <TooltipContent>Remove</TooltipContent>
                              </Tooltip>
                            </>
                          )}
                        </div>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          )}

          {/* Empty state */}
          {!hasItems && workingItems.length <= 1 && (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <p className="text-xs text-muted-foreground">
                No {title.toLowerCase()} added yet
              </p>
              <p className="text-xs text-muted-foreground mt-1">
                Click <Plus className="h-3 w-3 inline" /> to add one
              </p>
            </div>
          )}
        </div>
      </div>
    </TooltipProvider>
  )
}
