'use client'

import { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'

interface FieldDiff {
  key: string
  before: unknown
  after: unknown
}

interface RowDiff {
  status: 'added' | 'removed' | 'changed' | 'unchanged'
  fields: FieldDiff[]
}

interface TableDiff {
  tableName: string
  rows: RowDiff[]
  hasChanges: boolean
}

interface DiffData {
  versionA: { id: string; name: string }
  versionB: { id: string; name: string }
  diffs: TableDiff[]
  total_changes: number
}

const STATUS_COLORS: Record<string, string> = {
  added: 'bg-green-500/10 border-green-500/20',
  removed: 'bg-rose-500/10 border-rose-500/20',
  changed: 'bg-amber-500/10 border-amber-500/20',
}

export default function DiffPage() {
  const { id, otherId } = useParams<{ id: string; otherId: string }>()
  const [data, setData] = useState<DiffData | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!id || !otherId) return
    setLoading(true)
    fetch(`/api/admin/versions/${id}/diff/${otherId}`)
      .then(r => r.json())
      .then(setData)
      .finally(() => setLoading(false))
  }, [id, otherId])

  if (loading) return <div className="flex items-center justify-center h-64"><div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" /></div>
  if (!data) return <div className="text-rose-400">Failed to load diff</div>

  return (
    <div className="space-y-6">
      <Link href={`/pitch-admin/versions/${id}`} className="inline-flex items-center gap-2 text-sm text-white/50 hover:text-white/80">
        <ArrowLeft className="w-4 h-4" /> Back to version
      </Link>

      <div>
        <h1 className="text-2xl font-semibold text-white mb-1">Diff</h1>
        <p className="text-sm text-white/50">
          <span className="text-indigo-300">{data.versionA.name}</span>
          {' → '}
          <span className="text-purple-300">{data.versionB.name}</span>
          {' — '}{data.total_changes} change{data.total_changes !== 1 ? 's' : ''} across {data.diffs.length} table{data.diffs.length !== 1 ? 's' : ''}
        </p>
      </div>

      {data.diffs.length === 0 ? (
        <div className="bg-white/[0.04] border border-white/[0.06] rounded-2xl p-12 text-center text-white/50">
          No differences found
        </div>
      ) : (
        <div className="space-y-4">
          {data.diffs.map(table => (
            <details key={table.tableName} open className="bg-white/[0.04] border border-white/[0.06] rounded-2xl overflow-hidden">
              <summary className="px-5 py-3 cursor-pointer flex items-center justify-between hover:bg-white/[0.02]">
                <span className="text-sm font-semibold text-white capitalize">{table.tableName.replace(/_/g, ' ')}</span>
                <span className="text-xs text-white/40">
                  {table.rows.filter(r => r.status !== 'unchanged').length} change{table.rows.filter(r => r.status !== 'unchanged').length !== 1 ? 's' : ''}
                </span>
              </summary>
              <div className="px-5 pb-4 space-y-2">
                {table.rows.filter(r => r.status !== 'unchanged').map((row, i) => (
                  <div key={i} className={`rounded-lg border p-3 ${STATUS_COLORS[row.status] || ''}`}>
                    <div className="flex items-center gap-2 mb-2">
                      <span className={`text-[9px] px-1.5 py-0.5 rounded uppercase font-semibold ${
                        row.status === 'added' ? 'text-green-300' :
                        row.status === 'removed' ? 'text-rose-300' :
                        'text-amber-300'
                      }`}>{row.status}</span>
                    </div>
                    {row.fields.length > 0 && (
                      <div className="space-y-1">
                        {row.fields.map(f => (
                          <div key={f.key} className="text-xs font-mono grid grid-cols-12 gap-2">
                            <span className="col-span-3 text-white/60 truncate">{f.key}</span>
                            <span className="col-span-4 text-rose-300/80 truncate">{JSON.stringify(f.before)}</span>
                            <span className="col-span-1 text-white/30 text-center">→</span>
                            <span className="col-span-4 text-green-300/80 truncate">{JSON.stringify(f.after)}</span>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </details>
          ))}
        </div>
      )}
    </div>
  )
}
