"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { cn } from "@/lib/utils";
import type { LayeredTier, SourceRecordDto } from "@/lib/api/types";
import { StemeDBClient } from "@/lib/api";
import { SourceTierBadge, ConflictGauge, tierLabels, type SourceTier } from "@/components/skeptic";

function getConflictStatus(score: number): "Unanimous" | "Agreed" | "Contested" {
  if (score < 0.1) return "Unanimous";
  if (score < 0.4) return "Agreed";
  return "Contested";
}

function formatTimestamp(unixSeconds: number): string {
  const date = new Date(unixSeconds * 1000);
  return date.toLocaleString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

interface TierAccordionProps {
  tier: LayeredTier;
  isExpanded: boolean;
  onToggle: () => void;
}

export function TierAccordion({ tier, isExpanded, onToggle }: TierAccordionProps) {
  const safeTier = (tier.tier >= 0 && tier.tier <= 5 ? tier.tier : 5) as SourceTier;
  const tierLabel = tierLabels[safeTier] || tier.source_class;
  const conflictStatus = getConflictStatus(tier.conflict_score);

  const [sourceRecord, setSourceRecord] = useState<SourceRecordDto | null>(null);
  const [sourceLoading, setSourceLoading] = useState(false);

  useEffect(() => {
    if (!isExpanded || !tier.winner || sourceRecord || sourceLoading) return;
    setSourceLoading(true);
    const client = new StemeDBClient();
    client
      .getSource(tier.winner.source_hash)
      .then(setSourceRecord)
      .catch(() => {})
      .finally(() => setSourceLoading(false));
  }, [isExpanded, tier.winner, sourceRecord, sourceLoading]);

  return (
    <div className="border border-border rounded-lg overflow-hidden">
      <button
        type="button"
        onClick={onToggle}
        className={cn(
          "w-full px-4 py-3 flex items-center justify-between gap-4",
          "bg-card hover:bg-muted/50 transition-colors",
          "focus:outline-none focus:ring-2 focus:ring-ring focus:ring-inset"
        )}
        aria-expanded={isExpanded}
      >
        <div className="flex items-center gap-3">
          <SourceTierBadge tier={tier.tier} size="sm" />
          <span className="font-medium text-foreground">{tierLabel}</span>
          <span className="text-sm text-muted-foreground">
            {tier.candidates_count} candidate{tier.candidates_count !== 1 ? "s" : ""}
          </span>
        </div>

        <div className="flex items-center gap-4">
          <ConflictGauge
            score={tier.conflict_score}
            status={conflictStatus}
            variant="intra-tier"
            compact
          />
          <svg
            className={cn(
              "w-5 h-5 text-muted-foreground transition-transform",
              isExpanded && "rotate-90"
            )}
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M9 5l7 7-7 7"
            />
          </svg>
        </div>
      </button>

      {isExpanded && tier.winner && (
        <div className="px-4 py-4 border-t border-border bg-card/50 space-y-3">
          {/* Winner value */}
          <div>
            <span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
              Tier Winner
            </span>
            <p className="mt-1 text-foreground">
              {String(tier.winner.object.value)}
            </p>
          </div>

          {/* Metadata grid */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div>
              <span className="text-muted-foreground">Confidence</span>
              <p className="font-medium text-foreground">
                {(tier.winner.confidence * 100).toFixed(0)}%
              </p>
            </div>
            <div>
              <span className="text-muted-foreground">Lifecycle</span>
              <p className="font-medium text-foreground">{tier.winner.lifecycle}</p>
            </div>
            <div>
              <span className="text-muted-foreground">Resolution</span>
              <p className="font-medium text-foreground">
                {(tier.resolution_confidence * 100).toFixed(0)}%
              </p>
            </div>
            <div>
              <span className="text-muted-foreground">Source</span>
              {sourceLoading ? (
                <p className="font-mono text-xs text-muted-foreground animate-pulse">
                  Loading...
                </p>
              ) : sourceRecord ? (
                <p className="font-medium text-foreground truncate" title={sourceRecord.label}>
                  {sourceRecord.label}
                </p>
              ) : (
                <p className="font-mono text-xs text-foreground truncate" title={tier.winner.source_hash}>
                  {tier.winner.source_hash.slice(0, 12)}...
                </p>
              )}
            </div>
          </div>

          {/* Assertion timestamp */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div className="col-span-2">
              <span className="text-muted-foreground">Asserted at</span>
              <p className="font-medium text-foreground">
                {formatTimestamp(tier.winner.timestamp)}
              </p>
            </div>
          </div>

          {/* Narrative */}
          {tier.winner.narrative && (
            <div className="text-sm">
              <span className="text-muted-foreground">Narrative</span>
              <p className="mt-1 text-foreground whitespace-pre-wrap leading-relaxed">
                {tier.winner.narrative}
              </p>
            </div>
          )}

          {/* Source registry details */}
          {sourceLoading && (
            <div className="rounded border border-border bg-muted/30 p-2">
              <p className="text-xs text-muted-foreground animate-pulse">
                Loading source details...
              </p>
            </div>
          )}
          {!sourceLoading && sourceRecord && (
            <div className="rounded border border-border bg-muted/30 p-2 space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  Source Registry
                </span>
                <Link
                  href="/sources"
                  className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
                >
                  View in Source Registry →
                </Link>
              </div>
              <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
                <div>
                  <span className="text-muted-foreground">Label</span>
                  <p className="font-medium text-foreground">{sourceRecord.label}</p>
                </div>
                <div>
                  <span className="text-muted-foreground">Status</span>
                  <p className="font-medium text-foreground capitalize">{sourceRecord.status}</p>
                </div>
                {sourceRecord.url && (
                  <div className="col-span-2">
                    <span className="text-muted-foreground">URL</span>
                    <p className="font-mono text-foreground truncate" title={sourceRecord.url}>
                      <a
                        href={sourceRecord.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-blue-600 dark:text-blue-400 hover:underline"
                      >
                        {sourceRecord.url}
                      </a>
                    </p>
                  </div>
                )}
                {sourceRecord.notes && (
                  <div className="col-span-2">
                    <span className="text-muted-foreground">Notes</span>
                    <p className="text-foreground leading-relaxed">{sourceRecord.notes}</p>
                  </div>
                )}
                <div>
                  <span className="text-muted-foreground">Created</span>
                  <p className="text-foreground">{formatTimestamp(sourceRecord.created_at)}</p>
                </div>
                <div>
                  <span className="text-muted-foreground">Updated</span>
                  <p className="text-foreground">{formatTimestamp(sourceRecord.updated_at)}</p>
                </div>
              </div>
            </div>
          )}

          {/* Assertion hash */}
          <div className="pt-2 border-t border-border">
            <span className="text-xs text-muted-foreground">Assertion: </span>
            <code className="text-xs font-mono text-muted-foreground">
              {tier.winner.hash}
            </code>
          </div>
        </div>
      )}
    </div>
  );
}
