'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { Activity, Filter, GitBranch, Link2, RefreshCw, Search } from 'lucide-react';
import { createProxyFetch } from '@/lib/proxy-fetch';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  buildTimelineGroups,
  getProductLabel,
  getTimelineStats,
  TIMELINE_PRODUCT_OPTIONS,
  type TimelineItem,
} from '@/lib/timeline-view';

const apiFetch = createProxyFetch('/api/timeline');

function formatDate(iso: string) {
  return new Date(iso).toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

function badgeClassForActor(actorType: TimelineItem['actorType']) {
  switch (actorType) {
    case 'agent':
      return 'bg-blue-50 text-blue-700 border-0';
    case 'system':
      return 'bg-amber-50 text-amber-700 border-0';
    case 'device':
      return 'bg-violet-50 text-violet-700 border-0';
    default:
      return 'bg-emerald-50 text-emerald-700 border-0';
  }
}

export default function TimelinePage() {
  const [items, setItems] = useState<TimelineItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [userId, setUserId] = useState('');
  const [correlationId, setCorrelationId] = useState('');
  const [eventName, setEventName] = useState('all');
  const [artifactId, setArtifactId] = useState('');
  const [productId, setProductId] = useState('current');
  const [limit, setLimit] = useState('50');

  const loadData = useCallback(async () => {
    setLoading(true);
    const params = new URLSearchParams();
    if (userId.trim()) params.set('userId', userId.trim());
    if (correlationId.trim()) params.set('correlationId', correlationId.trim());
    if (artifactId.trim()) params.set('artifactId', artifactId.trim());
    if (eventName !== 'all') params.set('eventName', eventName);
    if (productId !== 'current') params.set('productId', productId);
    params.set('limit', limit);

    const query = params.toString();
    const data = await apiFetch(query ? `?${query}` : '');
    setItems(Array.isArray(data?.items) ? data.items : []);
    setLoading(false);
  }, [artifactId, correlationId, eventName, limit, productId, userId]);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  const stats = useMemo(() => getTimelineStats(items), [items]);
  const groups = useMemo(() => buildTimelineGroups(items), [items]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Ecosystem Timeline</h1>
          <p className="text-sm text-muted-foreground">
            Canonical timeline stream for the selected product scope, with correlation-chain
            grouping
          </p>
        </div>
        <Button variant="outline" onClick={() => void loadData()}>
          <RefreshCw className="mr-2 h-4 w-4" /> Refresh
        </Button>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Items</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{items.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Products</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.uniqueProducts}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Chains</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.groupedChains}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              With Artifacts
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.withArtifacts}</div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <Filter className="h-4 w-4" />
            Filters
          </CardTitle>
        </CardHeader>
        <CardContent className="grid gap-3 md:grid-cols-6">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="User ID"
              value={userId}
              onChange={event => setUserId(event.target.value)}
              className="pl-9"
            />
          </div>
          <Input
            placeholder="Correlation ID"
            value={correlationId}
            onChange={event => setCorrelationId(event.target.value)}
          />
          <Input
            placeholder="Artifact ID"
            value={artifactId}
            onChange={event => setArtifactId(event.target.value)}
          />
          <Select value={productId} onValueChange={setProductId}>
            <SelectTrigger>
              <SelectValue placeholder="Product scope" />
            </SelectTrigger>
            <SelectContent>
              {TIMELINE_PRODUCT_OPTIONS.map(option => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select value={eventName} onValueChange={setEventName}>
            <SelectTrigger>
              <SelectValue placeholder="Event type" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All events</SelectItem>
              <SelectItem value="capture.transcript.created">capture.transcript.created</SelectItem>
              <SelectItem value="artifact.created">artifact.created</SelectItem>
              <SelectItem value="artifact.linked">artifact.linked</SelectItem>
              <SelectItem value="memory.entry.created">memory.entry.created</SelectItem>
            </SelectContent>
          </Select>
          <Select value={limit} onValueChange={setLimit}>
            <SelectTrigger>
              <SelectValue placeholder="Limit" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="20">20</SelectItem>
              <SelectItem value="50">50</SelectItem>
              <SelectItem value="100">100</SelectItem>
            </SelectContent>
          </Select>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 text-center text-muted-foreground">Loading timeline...</div>
          ) : items.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">
              <Activity className="mx-auto mb-2 h-8 w-8 opacity-40" />
              No timeline items matched the current filters.
            </div>
          ) : (
            <div className="divide-y">
              {groups.map(group => (
                <div key={group.groupId} className="space-y-4 p-4">
                  <div className="flex flex-col gap-3 rounded-lg border bg-muted/20 p-3 md:flex-row md:items-start md:justify-between">
                    <div className="space-y-2">
                      <div className="flex flex-wrap items-center gap-2">
                        <Badge variant="secondary" className="gap-1">
                          <GitBranch className="h-3 w-3" />
                          {group.items.length > 1 ? `${group.items.length} events` : 'single event'}
                        </Badge>
                        {group.productIds.map(product => (
                          <Badge key={product} variant="outline">
                            {getProductLabel(product)}
                          </Badge>
                        ))}
                      </div>
                      <div className="text-sm text-muted-foreground">
                        {group.correlationId
                          ? `Correlation ${group.correlationId}`
                          : 'Standalone item without correlation ID'}
                      </div>
                    </div>
                    <div className="text-xs text-muted-foreground">
                      Latest activity {formatDate(group.latestOccurredAt)}
                    </div>
                  </div>

                  <div className="space-y-3">
                    {group.items.map(item => (
                      <div key={item.itemId} className="space-y-3 rounded-lg border p-4">
                        <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                          <div className="space-y-1">
                            <div className="flex flex-wrap items-center gap-2">
                              <h2 className="font-semibold">{item.title}</h2>
                              <Badge className={badgeClassForActor(item.actorType)}>
                                {item.actorType}
                              </Badge>
                              <Badge variant="outline">{getProductLabel(item.productId)}</Badge>
                              <Badge variant="outline">{item.eventName}</Badge>
                            </div>
                            {item.summary && (
                              <p className="text-sm text-muted-foreground">{item.summary}</p>
                            )}
                          </div>
                          <div className="text-xs text-muted-foreground">
                            {formatDate(item.occurredAt)}
                          </div>
                        </div>

                        <div className="grid gap-3 text-sm md:grid-cols-3">
                          <div>
                            <div className="mb-1 text-xs uppercase tracking-wide text-muted-foreground">
                              Correlation
                            </div>
                            <div className="font-mono text-xs">{item.correlationId || '—'}</div>
                          </div>
                          <div>
                            <div className="mb-1 text-xs uppercase tracking-wide text-muted-foreground">
                              Artifact Refs
                            </div>
                            <div className="space-y-1">
                              {item.artifactRefs.length === 0 ? (
                                <div className="text-xs text-muted-foreground">None</div>
                              ) : (
                                item.artifactRefs.map(ref => (
                                  <div key={ref} className="font-mono text-xs">
                                    {ref}
                                  </div>
                                ))
                              )}
                            </div>
                          </div>
                          <div>
                            <div className="mb-1 text-xs uppercase tracking-wide text-muted-foreground">
                              Related Events
                            </div>
                            <div className="space-y-1">
                              {item.relatedEventIds.length === 0 ? (
                                <div className="text-xs text-muted-foreground">None</div>
                              ) : (
                                item.relatedEventIds.map(ref => (
                                  <div
                                    key={ref}
                                    className="flex items-center gap-1 font-mono text-xs"
                                  >
                                    <Link2 className="h-3 w-3 text-muted-foreground" />
                                    {ref}
                                  </div>
                                ))
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
