import { formatDistanceToNow } from 'date-fns';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card } from '@/components/ui/card';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { ChevronDown, Edit, User } from 'lucide-react';
import { useState } from 'react';

interface EditHistoryEntryProps {
  editId: string;
  editorName: string;
  editorAvatar?: string;
  timestamp: string;
  changedFields: string[];
  editReason?: string;
  beforeData?: Record<string, any>;
  afterData?: Record<string, any>;
}

export function EditHistoryEntry({
  editId,
  editorName,
  editorAvatar,
  timestamp,
  changedFields,
  editReason,
  beforeData,
  afterData,
}: EditHistoryEntryProps) {
  const [isExpanded, setIsExpanded] = useState(false);

  const getFieldValue = (data: Record<string, any> | undefined, field: string): string => {
    if (!data || !(field in data)) return '—';
    const value = data[field];
    if (value === null || value === undefined) return '—';
    if (typeof value === 'object') return JSON.stringify(value, null, 2);
    return String(value);
  };

  return (
    <Card className="p-4">
      <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
        <div className="flex items-start gap-3">
          {/* Editor Avatar */}
          <Avatar className="h-8 w-8">
            <AvatarImage src={editorAvatar} alt={editorName} />
            <AvatarFallback>
              <User className="h-4 w-4" />
            </AvatarFallback>
          </Avatar>

          {/* Edit Info */}
          <div className="flex-1 space-y-2">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <span className="font-medium text-sm">{editorName}</span>
                <Badge variant="secondary" className="text-xs">
                  <Edit className="h-3 w-3 mr-1" />
                  {changedFields.length} field{changedFields.length !== 1 ? 's' : ''}
                </Badge>
              </div>
              <span className="text-xs text-muted-foreground">
                {formatDistanceToNow(new Date(timestamp), { addSuffix: true })}
              </span>
            </div>

            {/* Changed Fields Summary */}
            <div className="flex flex-wrap gap-1">
              {changedFields.slice(0, 3).map((field) => (
                <Badge key={field} variant="outline" className="text-xs">
                  {field}
                </Badge>
              ))}
              {changedFields.length > 3 && (
                <Badge variant="outline" className="text-xs">
                  +{changedFields.length - 3} more
                </Badge>
              )}
            </div>

            {/* Edit Reason */}
            {editReason && (
              <p className="text-sm text-muted-foreground italic">
                "{editReason}"
              </p>
            )}

            {/* Expand/Collapse Button */}
            <CollapsibleTrigger asChild>
              <Button variant="ghost" size="sm" className="h-8 px-2">
                <ChevronDown className={`h-4 w-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />
                <span className="ml-1">{isExpanded ? 'Hide' : 'Show'} Changes</span>
              </Button>
            </CollapsibleTrigger>
          </div>
        </div>

        {/* Detailed Changes */}
        <CollapsibleContent className="mt-3 space-y-3">
          {changedFields.map((field) => {
            const beforeValue = getFieldValue(beforeData, field);
            const afterValue = getFieldValue(afterData, field);

            return (
              <div key={field} className="border-l-2 border-muted pl-3 space-y-1">
                <div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {field}
                </div>
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div className="space-y-1">
                    <div className="text-xs text-muted-foreground">Before</div>
                    <div className="bg-destructive/10 text-destructive rounded p-2 font-mono text-xs break-all">
                      {beforeValue}
                    </div>
                  </div>
                  <div className="space-y-1">
                    <div className="text-xs text-muted-foreground">After</div>
                    <div className="bg-success/10 text-success rounded p-2 font-mono text-xs break-all">
                      {afterValue}
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </CollapsibleContent>
      </Collapsible>
    </Card>
  );
}
