'use client';

import { useMemo, useState } from 'react';
import Link from 'next/link';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible';
import { Separator } from '@/components/ui/separator';
import {
  ChevronRight,
  ChevronDown,
  ExternalLink,
  AlertTriangle,
  ArrowRight,
} from 'lucide-react';
import { ShareModal } from './share-modal';
import { AnalyzeButton } from './analyze-button';
import { AnalysisMarkdown } from './analysis-markdown';
import type { PersistedAnalysis, Visibility } from '@/lib/types/analyzer';
import { useUserTimezone } from '@/lib/hooks/use-user-timezone';

interface AnalysisViewProps {
  analysis: PersistedAnalysis;
}

const VISIBILITY_MARKER: Record<Visibility, string> = {
  customer_facing: '🟢',
  internal_only: '🔒',
  mixed: '🔄',
};

const VISIBILITY_LABEL: Record<Visibility, string> = {
  customer_facing: 'Customer-facing',
  internal_only: 'Internal only',
  mixed: 'Mixed (both)',
};

const SEVERITY_TONE: Record<string, string> = {
  high: 'border-red-500 bg-red-500/5',
  medium: 'border-amber-500 bg-amber-500/5',
  low: 'border-blue-500 bg-blue-500/5',
};

function ConfidenceBadge({ score }: { score: number | null }) {
  if (score === null) return null;
  const pct = Math.round(score * 100);
  const tone =
    score >= 0.8 ? 'bg-emerald-500/10 text-emerald-700 dark:text-emerald-400'
    : score >= 0.6 ? 'bg-amber-500/10 text-amber-700 dark:text-amber-400'
    : 'bg-red-500/10 text-red-700 dark:text-red-400';
  return (
    <Badge className={tone} variant="outline">
      Confidence {pct}%
    </Badge>
  );
}

function ModelBadges({ a }: { a: PersistedAnalysis }) {
  return (
    <div className="flex gap-1 flex-wrap">
      {a.haikuUsed && <Badge variant="secondary">Haiku</Badge>}
      {a.sonnetUsed && <Badge variant="secondary">Sonnet</Badge>}
      {a.opusUsed && <Badge variant="secondary">Opus</Badge>}
    </div>
  );
}

export function AnalysisView({ analysis: a }: AnalysisViewProps) {
  const tz = useUserTimezone();
  const [expandedEvent, setExpandedEvent] = useState<number | null>(null);
  const [nextStepOpen, setNextStepOpen] = useState(false);

  const timelineByTimestamp = useMemo(() => {
    const map = new Map<string, number>();
    (a.timeline ?? []).forEach((event, idx) => {
      if (!map.has(event.timestamp)) map.set(event.timestamp, idx);
    });
    return map;
  }, [a.timeline]);

  function jumpToEvent(timestamp: string) {
    const idx = timelineByTimestamp.get(timestamp);
    if (idx === undefined) return;
    setExpandedEvent(idx);
    document
      .getElementById(`timeline-event-${idx}`)
      ?.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }

  return (
    <div className="space-y-6">
      {/* 1. Header */}
      <Card>
        <CardHeader>
          <div className="flex flex-wrap items-start justify-between gap-4">
            <div className="space-y-1 min-w-0">
              <div className="flex items-center gap-2 flex-wrap">
                <Link
                  href={`/analyzer/ticket/${encodeURIComponent(a.ticketNumber)}`}
                  className="font-mono text-sm hover:underline"
                >
                  {a.ticketNumber}
                </Link>
                <span className="text-muted-foreground text-sm">
                  v{a.analysisVersion}
                </span>
                {a.needsHumanReview && (
                  <Badge variant="destructive">Needs review</Badge>
                )}
              </div>
              <CardTitle className="text-xl">
                AI Analysis &middot; {new Date(a.triggeredAt).toLocaleString(undefined, { timeZone: tz })}
              </CardTitle>
              <p className="text-muted-foreground text-sm">
                {a.totalInputTokens.toLocaleString()} in /{' '}
                {a.totalOutputTokens.toLocaleString()} out tokens · cost{' '}
                {`$${a.estimatedCostUsd.toFixed(4)}`}
              </p>
            </div>
            <div className="flex flex-col items-end gap-2 shrink-0">
              <div className="flex gap-2 items-center">
                <ModelBadges a={a} />
                <ConfidenceBadge score={a.confidenceScore} />
              </div>
              <div className="flex gap-2">
                <ShareModal analysisId={a.id} />
                <AnalyzeButton
                  ticketNumber={a.ticketNumber}
                  force
                  variant="outline"
                />
              </div>
            </div>
          </div>
        </CardHeader>
      </Card>

      {/* 2. Summary */}
      {a.summary && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base text-muted-foreground uppercase tracking-wide font-semibold">
              Summary
            </CardTitle>
          </CardHeader>
          <CardContent>
            <AnalysisMarkdown className="text-base">{a.summary}</AnalysisMarkdown>
          </CardContent>
        </Card>
      )}

      {/* 3. Next step */}
      {a.nextStep && (
        <Card className="border-primary/40 bg-primary/5">
          <CardHeader>
            <CardTitle className="text-base text-primary uppercase tracking-wide font-semibold flex items-center gap-2">
              <ArrowRight className="w-4 h-4" />
              Recommended Next Step
            </CardTitle>
          </CardHeader>
          <CardContent>
            <AnalysisMarkdown className="text-base prose-p:font-medium">
              {a.nextStep}
            </AnalysisMarkdown>
            {a.nextStepRationale && (
              <Collapsible
                open={nextStepOpen}
                onOpenChange={setNextStepOpen}
                className="mt-4 pt-4 border-t border-primary/20"
              >
                <CollapsibleTrigger asChild>
                  <Button variant="ghost" size="sm" className="-ml-2 h-8">
                    {nextStepOpen ? (
                      <ChevronDown className="w-4 h-4 mr-1" />
                    ) : (
                      <ChevronRight className="w-4 h-4 mr-1" />
                    )}
                    {nextStepOpen ? 'Hide rationale' : 'Show rationale'}
                  </Button>
                </CollapsibleTrigger>
                <CollapsibleContent>
                  <AnalysisMarkdown className="text-sm text-muted-foreground mt-3 pl-4 border-l-2 border-primary/30">
                    {a.nextStepRationale}
                  </AnalysisMarkdown>
                </CollapsibleContent>
              </Collapsible>
            )}
          </CardContent>
        </Card>
      )}

      {/* 4. Timeline */}
      {a.timeline && a.timeline.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Timeline</CardTitle>
          </CardHeader>
          <CardContent>
            <ol className="space-y-3 border-l-2 border-muted ml-2">
              {a.timeline.map((event, idx) => (
                <li
                  key={idx}
                  id={`timeline-event-${idx}`}
                  className="pl-4 relative -ml-px"
                >
                  <span className="absolute -left-2 top-1.5 w-3 h-3 rounded-full bg-background border-2 border-muted-foreground" />
                  <button
                    type="button"
                    onClick={() =>
                      setExpandedEvent(expandedEvent === idx ? null : idx)
                    }
                    className="text-left w-full hover:bg-accent/50 -mx-2 px-2 py-1 rounded"
                  >
                    <div className="flex items-start gap-2 flex-wrap text-sm">
                      <span title={VISIBILITY_LABEL[event.visibility]}>
                        {VISIBILITY_MARKER[event.visibility]}
                      </span>
                      <span className="font-mono text-xs text-muted-foreground shrink-0">
                        {new Date(event.timestamp).toLocaleString(undefined, { timeZone: tz })}
                      </span>
                      <span className="font-medium">{event.actor}</span>
                      <Badge variant="outline" className="text-xs">
                        {event.actor_type}
                      </Badge>
                      <Badge variant="outline" className="text-xs">
                        {event.source}
                      </Badge>
                    </div>
                    <p className="text-sm mt-1">{event.action}</p>
                  </button>
                </li>
              ))}
            </ol>
          </CardContent>
        </Card>
      )}

      {/* 5+6. What was done / should have been done — side by side on wide */}
      {((a.whatWasDone?.length ?? 0) > 0 ||
        (a.whatShouldHaveBeenDone?.length ?? 0) > 0) && (
        <div className="grid lg:grid-cols-2 gap-4">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">What was done</CardTitle>
            </CardHeader>
            <CardContent>
              <ul className="text-sm space-y-2 list-disc pl-5">
                {(a.whatWasDone ?? []).map((item, i) => (
                  <li key={i}>{item}</li>
                ))}
              </ul>
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle className="text-base">
                What should have been done
              </CardTitle>
            </CardHeader>
            <CardContent>
              <ul className="text-sm space-y-2 list-disc pl-5">
                {(a.whatShouldHaveBeenDone ?? []).map((item, i) => (
                  <li key={i}>{item}</li>
                ))}
              </ul>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 7. Gaps */}
      {a.gaps && a.gaps.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Gaps</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            {a.gaps.map((gap, i) => (
              <div
                key={i}
                className={`rounded-lg border-l-4 p-3 ${SEVERITY_TONE[gap.severity] ?? ''}`}
              >
                <div className="flex items-center gap-2">
                  <Badge
                    variant={
                      gap.severity === 'high'
                        ? 'destructive'
                        : gap.severity === 'medium'
                          ? 'default'
                          : 'secondary'
                    }
                  >
                    {gap.severity}
                  </Badge>
                  <p className="text-sm font-medium">{gap.description}</p>
                </div>
                {gap.evidence_timestamps.length > 0 && (
                  <div className="mt-2 text-xs text-muted-foreground">
                    Evidence:{' '}
                    {gap.evidence_timestamps.map((ts, j) => (
                      <button
                        key={j}
                        type="button"
                        onClick={() => jumpToEvent(ts)}
                        className="underline mr-2 font-mono"
                      >
                        {new Date(ts).toLocaleString(undefined, { timeZone: tz })}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </CardContent>
        </Card>
      )}

      {/* 8. Post-resolution analysis */}
      {a.postResolutionAnalysis && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base text-muted-foreground uppercase tracking-wide font-semibold">
              Post-Resolution Analysis
            </CardTitle>
          </CardHeader>
          <CardContent>
            <AnalysisMarkdown className="text-base">
              {a.postResolutionAnalysis}
            </AnalysisMarkdown>
          </CardContent>
        </Card>
      )}

      {/* 9. Human review flags */}
      {a.needsHumanReview && (
        <Card className="border-destructive/50 bg-destructive/5">
          <CardHeader>
            <CardTitle className="text-base flex items-center gap-2">
              <AlertTriangle className="w-4 h-4 text-destructive" />
              Human review flags
            </CardTitle>
          </CardHeader>
          <CardContent>
            <ul className="text-sm space-y-1 list-disc pl-5">
              {(a.humanReviewReasons ?? []).map((reason, i) => (
                <li key={i}>{reason}</li>
              ))}
            </ul>
          </CardContent>
        </Card>
      )}

      {/* 10. IT Glue references */}
      {a.itglueDocsReferenced.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">IT Glue references</CardTitle>
          </CardHeader>
          <CardContent>
            <ul className="text-sm space-y-2">
              {a.itglueDocsReferenced.map((doc) => (
                <li key={doc.id} className="flex items-start gap-2">
                  <Badge variant="outline">{doc.doc_type}</Badge>
                  <div className="min-w-0 flex-1">
                    {doc.url ? (
                      <a
                        href={doc.url}
                        target="_blank"
                        rel="noreferrer"
                        className="font-medium hover:underline inline-flex items-center gap-1"
                      >
                        {doc.name}
                        <ExternalLink className="w-3 h-3" />
                      </a>
                    ) : (
                      <span className="font-medium">{doc.name}</span>
                    )}
                    <p className="text-xs text-muted-foreground mt-0.5">
                      {doc.relevance_reason}
                    </p>
                  </div>
                </li>
              ))}
            </ul>
          </CardContent>
        </Card>
      )}

      {/* Expanded event detail (rendered separately so it floats independently) */}
      {expandedEvent !== null && a.timeline?.[expandedEvent] && (
        <Card className="border-dashed">
          <CardHeader>
            <CardTitle className="text-sm">Event detail</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2 text-sm">
            <p>
              <strong>{a.timeline[expandedEvent].actor}</strong> ·{' '}
              {new Date(a.timeline[expandedEvent].timestamp).toLocaleString(undefined, { timeZone: tz })}
            </p>
            <p>{a.timeline[expandedEvent].action}</p>
            <Separator />
            <p className="text-xs text-muted-foreground">
              Visibility: {VISIBILITY_LABEL[a.timeline[expandedEvent].visibility]}
              {' · '} Source: {a.timeline[expandedEvent].source}
              {' · '} Actor type: {a.timeline[expandedEvent].actor_type}
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
