"use client";

import { useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ChevronDown, ChevronUp, AlertTriangle, CheckCircle, Ban } from "lucide-react";
import type { AuthoredClaimDto } from "@/lib/api/types";

interface ClaimCardProps {
  claim: AuthoredClaimDto;
  onClick?: () => void;
}

function formatValue(value: AuthoredClaimDto["value"]): string {
  // Handle null/undefined
  if (value === null || value === undefined) return "null";

  // Value is untagged, so it's just boolean | number | string
  if (typeof value === "boolean") return String(value);
  if (typeof value === "number") return String(value);
  if (typeof value === "string") return value;

  // Fallback: stringify whatever we got
  return JSON.stringify(value);
}

function getStatusIcon(status: string) {
  switch (status) {
    case "active":
      return <CheckCircle className="h-3 w-3" />;
    case "deprecated":
      return <AlertTriangle className="h-3 w-3" />;
    case "superseded":
      return <Ban className="h-3 w-3" />;
    default:
      return null;
  }
}

function getStatusColor(status: string): string {
  switch (status) {
    case "active":
      return "bg-green-500/10 text-green-700 border-green-500/20";
    case "deprecated":
      return "bg-yellow-500/10 text-yellow-700 border-yellow-500/20";
    case "superseded":
      return "bg-gray-500/10 text-gray-700 border-gray-500/20";
    default:
      return "bg-gray-500/10 text-gray-700 border-gray-500/20";
  }
}

function getAuthorityColor(tier: string): string {
  switch (tier.toLowerCase()) {
    case "expert":
      return "bg-purple-500/10 text-purple-700 border-purple-500/20";
    case "team":
      return "bg-blue-500/10 text-blue-700 border-blue-500/20";
    case "community":
      return "bg-cyan-500/10 text-cyan-700 border-cyan-500/20";
    default:
      return "bg-gray-500/10 text-gray-700 border-gray-500/20";
  }
}

function getCategoryColor(category: string): string {
  switch (category.toLowerCase()) {
    case "architecture":
      return "bg-indigo-500/10 text-indigo-700 border-indigo-500/20";
    case "security":
      return "bg-red-500/10 text-red-700 border-red-500/20";
    case "performance":
      return "bg-orange-500/10 text-orange-700 border-orange-500/20";
    case "compatibility":
      return "bg-teal-500/10 text-teal-700 border-teal-500/20";
    case "correctness":
      return "bg-green-500/10 text-green-700 border-green-500/20";
    default:
      return "bg-gray-500/10 text-gray-700 border-gray-500/20";
  }
}

export function ClaimCard({ claim, onClick }: ClaimCardProps) {
  const [expanded, setExpanded] = useState(false);

  const handleExpandToggle = (e: React.MouseEvent) => {
    e.stopPropagation();
    setExpanded(!expanded);
  };

  return (
    <div
      className="border rounded-lg hover:bg-muted/50 transition-colors"
      onClick={onClick}
    >
      {/* Main Content */}
      <div className="p-4 space-y-3">
        {/* Header with badges */}
        <div className="flex items-start justify-between gap-3">
          <div className="flex-1 space-y-2">
            {/* Invariant - The main rule */}
            <h3 className="font-semibold text-foreground leading-tight">
              {claim.invariant}
            </h3>

            {/* Concept path and predicate/value */}
            <div className="flex flex-wrap items-center gap-2 text-xs">
              <code className="px-2 py-0.5 bg-muted rounded font-mono">
                {claim.concept_path}
              </code>
              <span className="text-muted-foreground">→</span>
              <code className="px-2 py-0.5 bg-muted rounded font-mono">
                {claim.predicate}
              </code>
              <span className="text-muted-foreground">{claim.comparison}</span>
              <code className="px-2 py-0.5 bg-muted rounded font-mono text-primary">
                {formatValue(claim.value)}
              </code>
            </div>
          </div>

          {/* Status badges */}
          <div className="flex flex-col gap-1.5 items-end">
            <Badge variant="outline" className={getStatusColor(claim.status)}>
              <span className="mr-1">{getStatusIcon(claim.status)}</span>
              {claim.status}
            </Badge>
            <Badge variant="outline" className={getAuthorityColor(claim.authority_tier)}>
              {claim.authority_tier}
            </Badge>
            <Badge variant="outline" className={getCategoryColor(claim.category)}>
              {claim.category}
            </Badge>
          </div>
        </div>

        {/* Expand/Collapse button */}
        <Button
          variant="ghost"
          size="sm"
          onClick={handleExpandToggle}
          className="w-full text-xs"
        >
          {expanded ? (
            <>
              <ChevronUp className="h-3 w-3 mr-1" />
              Hide Details
            </>
          ) : (
            <>
              <ChevronDown className="h-3 w-3 mr-1" />
              Show Details
            </>
          )}
        </Button>
      </div>

      {/* Expanded Details */}
      {expanded && (
        <div className="border-t bg-muted/30 p-4 space-y-4">
          {/* Claim ID */}
          <div>
            <p className="text-xs font-medium text-muted-foreground mb-1">Claim ID</p>
            <code className="text-xs font-mono">{claim.id}</code>
          </div>

          {/* Consequence - What breaks if violated */}
          <div className="bg-destructive/5 border border-destructive/20 rounded-md p-3">
            <div className="flex items-start gap-2">
              <AlertTriangle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
              <div>
                <p className="text-xs font-medium text-destructive mb-1">
                  Consequence if violated:
                </p>
                <p className="text-sm text-destructive/90">{claim.consequence}</p>
              </div>
            </div>
          </div>

          {/* Provenance */}
          <div>
            <p className="text-xs font-medium text-muted-foreground mb-1">Provenance</p>
            <p className="text-sm">{claim.provenance}</p>
          </div>

          {/* Evidence */}
          {claim.evidence && claim.evidence.length > 0 && (
            <div>
              <p className="text-xs font-medium text-muted-foreground mb-1">Evidence</p>
              <ul className="space-y-1">
                {claim.evidence.map((ev, idx) => (
                  <li key={idx} className="text-sm flex items-start gap-2">
                    <span className="text-muted-foreground mt-0.5">•</span>
                    <span>{ev}</span>
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Metadata */}
          <div className="grid grid-cols-2 gap-4 text-xs">
            <div>
              <p className="font-medium text-muted-foreground mb-1">Created By</p>
              <p>{claim.created_by}</p>
            </div>
            <div>
              <p className="font-medium text-muted-foreground mb-1">Created At</p>
              <p>{new Date(claim.created_at).toLocaleString()}</p>
            </div>
            {claim.updated_at && (
              <div>
                <p className="font-medium text-muted-foreground mb-1">Updated At</p>
                <p>{new Date(claim.updated_at).toLocaleString()}</p>
              </div>
            )}
            {claim.supersedes && (
              <div className="col-span-2">
                <p className="font-medium text-muted-foreground mb-1">Supersedes</p>
                <code className="text-xs font-mono">{claim.supersedes}</code>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
