"use client";

import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { History, Clock } from "lucide-react";
import { format } from "date-fns";
import { ProjectVersion } from "@/types/project";

interface VersionsPanelProps {
  versions: ProjectVersion[];
  onRestoreVersion: (versionId: string) => void;
}

const VersionsPanel = ({ versions, onRestoreVersion }: VersionsPanelProps) => {
  const [expandedVersion, setExpandedVersion] = useState<string | null>(null);

  const toggleExpand = (versionId: string) => {
    setExpandedVersion(expandedVersion === versionId ? null : versionId);
  };

  // Helper function to safely format dates
  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        return "Invalid date";
      }
      return format(date, "MMM d, yyyy h:mm a");
    } catch (error) {
      console.error("Error formatting date:", error);
      return "Invalid date";
    }
  };

  return (
    <div className="p-4 bg-background h-full overflow-y-auto">
      <div className="flex items-center mb-4">
        <History className="h-5 w-5 mr-2 text-foreground" />
        <h3 className="font-bold text-lg text-foreground">Version History</h3>
      </div>
      
      {versions.length === 0 ? (
        <div className="text-center py-8 text-muted-foreground">
          <Clock className="h-12 w-12 mx-auto mb-2 opacity-50" />
          <p>No versions found</p>
          <p className="text-sm mt-1">Your project versions will appear here</p>
        </div>
      ) : (
        <div className="space-y-3">
          {versions.map((version, index) => {
            const versionNumber = versions.length - index;
            const isCurrent = index === 0;

            return (
              <Card key={version.id} className="bg-card border border-border">
                <CardContent className="p-4">
                  <div className="flex justify-between items-start">
                    <div>
                      <div className="flex items-center">
                        <h4 className="font-medium text-foreground">Version {versionNumber}</h4>
                        {isCurrent && (
                          <Badge variant="secondary" className="ml-2 bg-primary/10 text-primary">
                            Current
                          </Badge>
                        )}
                      </div>
                      <p className="text-xs text-muted-foreground mt-1 flex items-center">
                        <Clock className="h-3 w-3 mr-1" />
                        {formatDate(version.createdAt)}
                      </p>
                    </div>
                    <Button 
                      variant="outline" 
                      size="sm" 
                      onClick={() => onRestoreVersion(version.id)}
                      disabled={isCurrent}
                      className="text-xs"
                    >
                      Restore
                    </Button>
                  </div>
                  
                  {version.messages && version.messages.length > 0 && (
                    <div className="mt-3">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="p-0 h-auto text-muted-foreground hover:text-foreground text-xs"
                        onClick={() => toggleExpand(version.id)}
                      >
                        {expandedVersion === version.id ? "Hide Prompt" : "Show Prompt"}
                      </Button>
                      
                      {expandedVersion === version.id && (
                        <div className="mt-2 p-3 bg-muted rounded-md">
                          <p className="text-sm text-foreground">
                            {version.messages.find(m => m.role === 'user')?.content || 'No prompt found'}
                          </p>
                        </div>
                      )}
                    </div>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default VersionsPanel;