'use client';

import { useEffect, 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 { Skeleton } from '@/components/ui/skeleton';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { PageHeader } from '@/components/navigation/page-header';
import { useUserTimezone } from '@/lib/hooks/use-user-timezone';

interface WriteRow {
  id: string;
  audit_id: string | null;
  asset_type: 'flexible_asset';
  asset_id: string;
  field_name: string;
  before_value: unknown;
  after_value: unknown;
  performed_by_user_id: string | null;
  performed_at: string;
  status: 'pending' | 'committed' | 'failed' | 'reverted';
  error_message: string | null;
}

const STATUSES: Array<WriteRow['status'] | 'all'> = [
  'all',
  'committed',
  'reverted',
  'failed',
  'pending',
];

function statusVariant(
  s: WriteRow['status']
): 'default' | 'secondary' | 'destructive' | 'outline' {
  switch (s) {
    case 'committed':
      return 'default';
    case 'reverted':
      return 'secondary';
    case 'failed':
      return 'destructive';
    default:
      return 'outline';
  }
}

export default function ItglueWritesPage() {
  const tz = useUserTimezone();
  const [rows, setRows] = useState<WriteRow[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] =
    useState<WriteRow['status'] | 'all'>('all');

  async function load(): Promise<void> {
    try {
      const url =
        statusFilter === 'all'
          ? '/api/analyzer/itglue/writes'
          : `/api/analyzer/itglue/writes?status=${statusFilter}`;
      const res = await fetch(url);
      if (!res.ok) {
        const data = (await res.json().catch(() => ({}))) as { error?: string };
        throw new Error(data.error ?? `Request failed: ${res.status}`);
      }
      const data = (await res.json()) as { writes: WriteRow[] };
      setRows(data.writes);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    }
  }

  useEffect(() => {
    void load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [statusFilter]);

  return (
    <>
      <PageHeader
        title="IT Glue Writes"
        description="Every PATCH to IT Glue from Pulse, with before/after diffs and revert history."
        breadcrumbs={[{ label: 'Admin', href: '/admin' }, { label: 'IT Glue Writes' }]}
        accent
      />
      <div className="container mx-auto px-6 py-6 max-w-5xl space-y-6">
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between gap-4 flex-wrap">
            <div>
              <CardTitle>IT Glue write log</CardTitle>
              <p className="text-sm text-muted-foreground mt-1">
                Every PATCH to IT Glue from Pulse, with before/after diffs and
                revert history.
              </p>
            </div>
            <div className="flex items-center gap-1">
              {STATUSES.map((s) => (
                <Button
                  key={s}
                  variant={statusFilter === s ? 'secondary' : 'ghost'}
                  size="sm"
                  onClick={() => setStatusFilter(s)}
                >
                  {s}
                </Button>
              ))}
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {error && (
            <Alert variant="destructive" className="mb-4">
              <AlertTitle>Couldn&rsquo;t load writes</AlertTitle>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}
          {rows === null && !error ? (
            <div className="space-y-2">
              <Skeleton className="h-12 w-full" />
              <Skeleton className="h-12 w-full" />
              <Skeleton className="h-12 w-full" />
            </div>
          ) : rows && rows.length === 0 ? (
            <p className="text-sm text-muted-foreground">No writes recorded yet.</p>
          ) : (
            <ul className="divide-y">
              {(rows ?? []).map((w) => (
                <li key={w.id} className="py-3">
                  <div className="flex items-start justify-between gap-3 flex-wrap">
                    <div className="min-w-0 flex-1">
                      <p className="text-sm">
                        <Link
                          href={`/analyzer/itglue/applications/${w.asset_id}`}
                          className="font-mono hover:underline"
                        >
                          {w.asset_id}
                        </Link>
                        {' · '}
                        <span className="font-medium">{w.field_name}</span>
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">
                        {new Date(w.performed_at).toLocaleString(undefined, { timeZone: tz })}
                      </p>
                      <p className="text-xs mt-1 break-words">
                        <span className="text-muted-foreground">Before: </span>
                        <span className="font-mono">
                          {w.before_value === null || w.before_value === undefined
                            ? '(empty)'
                            : JSON.stringify(w.before_value).slice(0, 200)}
                        </span>
                      </p>
                      <p className="text-xs mt-0.5 break-words">
                        <span className="text-muted-foreground">After: </span>
                        <span className="font-mono">
                          {JSON.stringify(w.after_value).slice(0, 200)}
                        </span>
                      </p>
                      {w.error_message && (
                        <p className="text-xs mt-1 text-destructive">
                          Error: {w.error_message}
                        </p>
                      )}
                    </div>
                    <Badge variant={statusVariant(w.status)}>{w.status}</Badge>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>
      </div>
    </>
  );
}
