"use client"

import { useState } from "react"
import { ChevronDown, ChevronRight, Copy, Check } from "lucide-react"
import { Button } from "@/components/ui/button"

interface DiffDisplayProps {
  oldText: string
  newText: string
  title?: string
  language?: string
}

interface DiffLine {
  type: 'added' | 'removed' | 'unchanged'
  content: string
  oldLineNumber?: number
  newLineNumber?: number
}

export function DiffDisplay({ oldText, newText, title = "Code Diff", language = "text" }: DiffDisplayProps) {
  const [isExpanded, setIsExpanded] = useState(false)
  const [copied, setCopied] = useState(false)

  // Simple diff algorithm - split into lines and compare
  const generateDiff = (): DiffLine[] => {
    const oldLines = oldText.split('\n')
    const newLines = newText.split('\n')
    const diff: DiffLine[] = []
    
    let oldIndex = 0
    let newIndex = 0
    let oldLineNum = 1
    let newLineNum = 1

    while (oldIndex < oldLines.length || newIndex < newLines.length) {
      const oldLine = oldLines[oldIndex]
      const newLine = newLines[newIndex]

      if (oldIndex >= oldLines.length) {
        // Only new lines left
        diff.push({
          type: 'added',
          content: newLine,
          newLineNumber: newLineNum
        })
        newIndex++
        newLineNum++
      } else if (newIndex >= newLines.length) {
        // Only old lines left
        diff.push({
          type: 'removed',
          content: oldLine,
          oldLineNumber: oldLineNum
        })
        oldIndex++
        oldLineNum++
      } else if (oldLine === newLine) {
        // Lines are the same
        diff.push({
          type: 'unchanged',
          content: oldLine,
          oldLineNumber: oldLineNum,
          newLineNumber: newLineNum
        })
        oldIndex++
        newIndex++
        oldLineNum++
        newLineNum++
      } else {
        // Lines are different - check if it's an addition or removal
        const oldLineNext = oldLines[oldIndex + 1]
        const newLineNext = newLines[newIndex + 1]

        if (oldLineNext === newLine) {
          // Old line was removed
          diff.push({
            type: 'removed',
            content: oldLine,
            oldLineNumber: oldLineNum
          })
          oldIndex++
          oldLineNum++
        } else if (newLineNext === oldLine) {
          // New line was added
          diff.push({
            type: 'added',
            content: newLine,
            newLineNumber: newLineNum
          })
          newIndex++
          newLineNum++
        } else {
          // Both lines changed
          diff.push({
            type: 'removed',
            content: oldLine,
            oldLineNumber: oldLineNum
          })
          diff.push({
            type: 'added',
            content: newLine,
            newLineNumber: newLineNum
          })
          oldIndex++
          newIndex++
          oldLineNum++
          newLineNum++
        }
      }
    }

    return diff
  }

  const diff = generateDiff()
  const hasChanges = diff.some(line => line.type !== 'unchanged')

  const copyToClipboard = async () => {
    const fullDiff = diff.map(line => {
      const prefix = line.type === 'added' ? '+' : line.type === 'removed' ? '-' : ' '
      const oldNum = line.oldLineNumber ? line.oldLineNumber.toString().padStart(3) : '   '
      const newNum = line.newLineNumber ? line.newLineNumber.toString().padStart(3) : '   '
      return `${prefix} ${oldNum}|${newNum} ${line.content}`
    }).join('\n')

    try {
      await navigator.clipboard.writeText(fullDiff)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch (err) {
      console.error('Failed to copy diff:', err)
    }
  }

  if (!hasChanges) {
    return (
      <div className="rounded-lg border border-neutral-800 bg-neutral-900/50 p-4">
        <div className="flex items-center gap-2 text-sm text-neutral-400">
          <Check className="h-4 w-4 text-green-500" />
          <span>No changes detected</span>
        </div>
      </div>
    )
  }

  return (
    <div className="rounded-lg border border-neutral-800 bg-neutral-900/50 overflow-hidden">
      <div className="flex items-center justify-between px-4 py-3 bg-neutral-800/50 border-b border-neutral-800">
        <div className="flex items-center gap-2">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setIsExpanded(!isExpanded)}
            className="h-6 w-6 p-0 text-neutral-400 hover:text-white"
          >
            {isExpanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
          </Button>
          <span className="text-sm font-medium text-white">{title}</span>
          <span className="text-xs text-neutral-500">({language})</span>
        </div>
        <Button
          variant="ghost"
          size="sm"
          onClick={copyToClipboard}
          className="h-6 w-6 p-0 text-neutral-400 hover:text-white"
        >
          {copied ? <Check className="h-4 w-4 text-green-500" /> : <Copy className="h-4 w-4" />}
        </Button>
      </div>

      {isExpanded && (
        <div className="overflow-x-auto">
          <div className="font-mono text-sm">
            {diff.map((line, index) => (
              <div
                key={index}
                className={`flex items-start gap-2 px-4 py-1 ${
                  line.type === 'added'
                    ? 'bg-green-500/10 border-l-4 border-green-500'
                    : line.type === 'removed'
                    ? 'bg-red-500/10 border-l-4 border-red-500'
                    : 'bg-transparent'
                }`}
              >
                <div className="flex-shrink-0 w-12 text-xs text-neutral-500 select-none">
                  {line.oldLineNumber && line.newLineNumber ? (
                    `${line.oldLineNumber}|${line.newLineNumber}`
                  ) : line.oldLineNumber ? (
                    `${line.oldLineNumber}|   `
                  ) : line.newLineNumber ? (
                    `   |${line.newLineNumber}`
                  ) : (
                    '   |   '
                  )}
                </div>
                <div className="flex-shrink-0 w-4 text-center text-xs select-none">
                  {line.type === 'added' ? (
                    <span className="text-green-500">+</span>
                  ) : line.type === 'removed' ? (
                    <span className="text-red-500">-</span>
                  ) : (
                    <span className="text-neutral-500"> </span>
                  )}
                </div>
                <div className={`flex-1 ${
                  line.type === 'added'
                    ? 'text-green-400'
                    : line.type === 'removed'
                    ? 'text-red-400'
                    : 'text-neutral-300'
                }`}>
                  <code>{line.content || ' '}</code>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
