import { useState, useEffect, useCallback } from 'react'
import { Code2, ImageIcon, Plus, Trash2, ChevronDown, ChevronRight } from 'lucide-react'
import { cn } from '@/lib/utils'
import { getSupportingData, deleteSupportingData } from '@/api/supportingData'
import type { SupportingDataItem } from '@/api/supportingData'
import { AddSupportingDataModal } from './AddSupportingDataModal'
import { toast } from '@/lib/toast'

interface SupportingDataPanelProps {
  sessionId: string
}

export function SupportingDataPanel({ sessionId }: SupportingDataPanelProps) {
  const [items, setItems] = useState<SupportingDataItem[]>([])
  const [isExpanded, setIsExpanded] = useState(false)
  const [showAddModal, setShowAddModal] = useState(false)
  const [isLoading, setIsLoading] = useState(false)

  const loadItems = useCallback(async () => {
    setIsLoading(true)
    try {
      const data = await getSupportingData(sessionId)
      setItems(data)
    } catch (err) {
      console.error('Failed to load supporting data:', err)
    } finally {
      setIsLoading(false)
    }
  }, [sessionId])

  useEffect(() => {
    loadItems()
  }, [loadItems])

  const handleDelete = async (itemId: string) => {
    try {
      await deleteSupportingData(sessionId, itemId)
      setItems((prev) => prev.filter((item) => item.id !== itemId))
      toast.success('Supporting data removed')
    } catch (err) {
      console.error('Failed to delete supporting data:', err)
      toast.error('Failed to remove item')
    }
  }

  const handleAdded = () => {
    loadItems()
    setIsExpanded(true)
  }

  return (
    <div className="rounded-xl border border-border bg-card/50">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3">
        <button
          type="button"
          onClick={() => setIsExpanded(!isExpanded)}
          className="flex items-center gap-2 text-sm font-medium text-foreground hover:text-foreground/80"
        >
          {isExpanded ? (
            <ChevronDown className="h-4 w-4 text-muted-foreground" />
          ) : (
            <ChevronRight className="h-4 w-4 text-muted-foreground" />
          )}
          Supporting Data
          {items.length > 0 && (
            <span className="rounded-full bg-accent px-2 py-0.5 text-xs text-muted-foreground">
              {items.length}
            </span>
          )}
        </button>
        <button
          type="button"
          onClick={() => setShowAddModal(true)}
          className={cn(
            'flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium',
            'bg-primary text-white hover:brightness-110 active:scale-[0.98] transition-all'
          )}
        >
          <Plus className="h-3.5 w-3.5" />
          Add
        </button>
      </div>

      {/* Items list */}
      {isExpanded && (
        <div className="border-t border-border px-4 py-2">
          {isLoading && items.length === 0 ? (
            <p className="py-4 text-center text-xs text-muted-foreground">Loading...</p>
          ) : items.length === 0 ? (
            <p className="py-4 text-center text-xs text-muted-foreground">
              No supporting data yet. Add text snippets or screenshots to include in exports.
            </p>
          ) : (
            <div className="space-y-2 py-1">
              {items.map((item) => (
                <div
                  key={item.id}
                  className={cn(
                    'flex items-start gap-3 rounded-lg border border-border bg-card/30 px-3 py-2.5',
                    'group transition-colors hover:border-[rgba(255,255,255,0.12)]'
                  )}
                >
                  <span className="mt-0.5 shrink-0 text-muted-foreground">
                    {item.data_type === 'text_snippet' ? (
                      <Code2 className="h-4 w-4" />
                    ) : (
                      <ImageIcon className="h-4 w-4" />
                    )}
                  </span>
                  <div className="min-w-0 flex-1">
                    <p className="text-sm font-medium text-foreground">{item.label}</p>
                    {item.data_type === 'text_snippet' && item.content && (
                      <p className="mt-0.5 truncate text-xs font-mono text-muted-foreground">
                        {item.content.length > 120 ? item.content.slice(0, 120) + '...' : item.content}
                      </p>
                    )}
                    {item.data_type === 'screenshot' && item.content && (
                      <img
                        src={`data:${item.content_type || 'image/png'};base64,${item.content}`}
                        alt={item.label}
                        className="mt-1 max-h-16 rounded border border-border object-contain"
                      />
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={() => handleDelete(item.id)}
                    className="shrink-0 text-muted-foreground opacity-0 transition-opacity hover:text-rose-500 group-hover:opacity-100"
                    title="Remove"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Add Modal */}
      <AddSupportingDataModal
        isOpen={showAddModal}
        onClose={() => setShowAddModal(false)}
        sessionId={sessionId}
        onAdded={handleAdded}
      />
    </div>
  )
}

export default SupportingDataPanel
