'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { AlertCircle, Bell, Clock3, Loader2, RefreshCw, ArrowRight } from 'lucide-react';

import { listNotifications } from '@/lib/api';
import type { NotificationRun } from '@/types';
import { pickAppText } from '@/lib/i18n/core';
import { useAppI18n } from '@/lib/i18n/provider';
import { containedLongTextClass } from '@/lib/text-wrapping';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';

export default function NotificationsPage() {
  const { locale } = useAppI18n();
  const [items, setItems] = useState<NotificationRun[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = React.useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      setItems(await listNotifications());
    } catch (err: any) {
      setError(err.message || pickAppText(locale, '加载通知失败', 'Failed to load notifications'));
    } finally {
      setLoading(false);
    }
  }, [locale]);

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

  const formatTime = (value?: string | null) => {
    if (!value) return '-';
    return new Date(value).toLocaleString(locale, { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
  };

  return (
    <main className="mx-auto flex h-[calc(100vh-4rem)] max-w-6xl flex-col px-4 py-6 sm:px-6 sm:py-8">
      <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
        <div className="min-w-0">
          <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight">
            <Bell className="h-5 w-5" />
            {pickAppText(locale, '通知', 'Notifications')}
          </h1>
          <p className="mt-1 max-w-2xl text-sm text-muted-foreground">
            {pickAppText(locale, '定时任务生成的日报、提醒和总结会固定出现在这里。', 'Scheduled reports, reminders, and summaries appear here.')}
          </p>
        </div>
        <Button onClick={() => void load()} variant="outline" size="sm" className="h-11">
          <RefreshCw className="mr-2 h-4 w-4" />
          {pickAppText(locale, '刷新', 'Refresh')}
        </Button>
      </div>

      {error && (
        <Card className="mb-4 border-destructive">
          <CardContent className="flex items-center gap-2 pt-6 text-sm text-destructive">
            <AlertCircle className="h-4 w-4" />
            {error}
          </CardContent>
        </Card>
      )}

      <div className="min-h-0 flex-1 overflow-auto rounded-lg border border-[#E6E1DE] bg-white">
        {loading ? (
          <div className="flex h-full items-center justify-center text-muted-foreground">
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            {pickAppText(locale, '加载中', 'Loading')}
          </div>
        ) : items.length === 0 ? (
          <div className="flex h-full flex-col items-center justify-center text-muted-foreground">
            <Bell className="mb-3 h-10 w-10 opacity-40" />
            <p className="font-medium">{pickAppText(locale, '暂无通知', 'No notifications yet')}</p>
          </div>
        ) : (
          <div className="divide-y divide-[#E6E1DE]">
            {items.map((item) => (
              <Link
                key={item.scheduled_run_id}
                href={`/notifications/${encodeURIComponent(item.scheduled_run_id)}`}
                className="grid min-w-0 gap-3 px-4 py-4 transition-colors hover:bg-[#F7F6F5] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset sm:px-5 md:grid-cols-[minmax(0,1fr)_180px_110px_24px]"
              >
                <div className="min-w-0">
                  <div className="flex min-w-0 items-center gap-2">
                    <span className={`min-w-0 flex-1 font-medium ${containedLongTextClass}`}>{item.title || item.job_name}</span>
                    {item.engaged && <Badge variant="secondary" className="shrink-0">{pickAppText(locale, '已接入 Task', 'Task linked')}</Badge>}
                    {item.status === 'error' && <Badge variant="destructive" className="shrink-0">{pickAppText(locale, '错误', 'Error')}</Badge>}
                  </div>
                  <p className={`mt-1 line-clamp-2 text-sm text-muted-foreground ${containedLongTextClass}`}>{item.output || item.message}</p>
                </div>
                <div className="flex min-w-0 items-center gap-2 text-sm text-muted-foreground">
                  <Clock3 className="h-4 w-4" />
                  {formatTime(item.started_at)}
                </div>
                <div className={`text-sm text-muted-foreground ${containedLongTextClass}`}>{item.job_name}</div>
                <ArrowRight className="hidden h-4 w-4 self-center text-muted-foreground md:block" />
              </Link>
            ))}
          </div>
        )}
      </div>
    </main>
  );
}
