'use client'

import { useState } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Clock, RotateCcw, GitCompare } from 'lucide-react'
import { VersionComparison } from './VersionComparison'
import type { Version } from '@/lib/services/versionControl'

interface VersionHistoryProps {
  versions: Version[]
  onRestore?: (version: Version) => void
  onCompare?: (version1: Version, version2: Version) => void
}

export function VersionHistory({ versions, onRestore, onCompare }: VersionHistoryProps) {
  const [selectedVersion1, setSelectedVersion1] = useState<string>('')
  const [selectedVersion2, setSelectedVersion2] = useState<string>('')
  const [comparison, setComparison] = useState<{ v1: Version; v2: Version } | null>(null)

  const sortedVersions = [...versions].sort(
    (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
  )

  const handleCompare = () => {
    if (!selectedVersion1 || !selectedVersion2) return
    const v1 = versions.find((v) => v.id === selectedVersion1)
    const v2 = versions.find((v) => v.id === selectedVersion2)
    if (v1 && v2) {
      setComparison({ v1, v2 })
      onCompare?.(v1, v2)
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Version History</CardTitle>
        <CardDescription>
          {versions.length} version{versions.length !== 1 ? 's' : ''} available
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Compare versions */}
        {versions.length >= 2 && (
          <div className="p-4 bg-studio-medium/20 rounded-lg border border-studio-medium">
            <div className="flex items-center gap-2 mb-2">
              <GitCompare className="h-4 w-4 text-studio-medium" />
              <span className="text-sm font-medium">Compare Versions</span>
            </div>
            <div className="flex gap-2">
              <Select value={selectedVersion1} onValueChange={setSelectedVersion1}>
                <SelectTrigger className="flex-1">
                  <SelectValue placeholder="Select version 1" />
                </SelectTrigger>
                <SelectContent>
                  {sortedVersions.map((v) => (
                    <SelectItem key={v.id} value={v.id}>
                      v{v.version} - {new Date(v.timestamp).toLocaleString()}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={selectedVersion2} onValueChange={setSelectedVersion2}>
                <SelectTrigger className="flex-1">
                  <SelectValue placeholder="Select version 2" />
                </SelectTrigger>
                <SelectContent>
                  {sortedVersions.map((v) => (
                    <SelectItem key={v.id} value={v.id}>
                      v{v.version} - {new Date(v.timestamp).toLocaleString()}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Button
                onClick={handleCompare}
                disabled={!selectedVersion1 || !selectedVersion2}
                size="sm"
              >
                Compare
              </Button>
            </div>
          </div>
        )}

        {/* Version list */}
        <div className="space-y-2 max-h-96 overflow-y-auto">
          {sortedVersions.map((version) => (
            <div
              key={version.id}
              className="p-4 border border-studio-medium rounded-lg hover:border-studio-light transition-colors"
            >
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-2">
                    <Badge variant="outline">v{version.version}</Badge>
                    <span className="text-sm text-studio-medium">
                      <Clock className="h-3 w-3 inline mr-1" />
                      {new Date(version.timestamp).toLocaleString()}
                    </span>
                    {version.userId && (
                      <span className="text-xs text-studio-medium">by {version.userId}</span>
                    )}
                  </div>
                  {version.comment && (
                    <p className="text-sm text-studio-light mb-2">{version.comment}</p>
                  )}
                  {version.changes.length > 0 && (
                    <div className="text-xs text-studio-medium">
                      {version.changes.length} change{version.changes.length !== 1 ? 's' : ''}:
                      <div className="mt-1 space-y-1">
                        {version.changes.slice(0, 3).map((change, idx) => (
                          <div key={idx} className="pl-2">
                            • {change.field}: {String(change.before)} → {String(change.after)}
                          </div>
                        ))}
                        {version.changes.length > 3 && (
                          <div className="pl-2 text-studio-medium">
                            ... and {version.changes.length - 3} more
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>
                {onRestore && version.version !== sortedVersions[0]?.version && (
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => onRestore(version)}
                    className="ml-4"
                  >
                    <RotateCcw className="h-4 w-4 mr-2" />
                    Restore
                  </Button>
                )}
              </div>
            </div>
          ))}
        </div>

        {comparison && (
          <div className="mt-6">
            <VersionComparison version1={comparison.v1} version2={comparison.v2} />
            <Button
              variant="outline"
              className="mt-4"
              onClick={() => setComparison(null)}
            >
              Close Comparison
            </Button>
          </div>
        )}
      </CardContent>
    </Card>
  )
}

