'use client';

import { ArrowLeft, Download, Loader2, Printer } from 'lucide-react';
import { useParams } from 'next/navigation';
import * as React from 'react';
import { ReportChartsGrid } from '@/components/reports/report-chart';
import { ReportStatusBadge } from '@/components/reports/report-status-badge';
import { ReportTypeBadge } from '@/components/reports/report-type-badge';
import { Button } from '@/components/ui/button';
import { Link } from '@/i18n/navigation';
import { useReport, useReportStatus } from '@/lib/hooks/use-reports';

interface ReportSection {
  title: string;
  content?: string;
  data?: unknown;
  charts?: Record<string, unknown>;
  projects?: unknown[];
  summary?: unknown;
}

export default function ReportViewerPage() {
  const routeParams = useParams();
  const reportId = routeParams['id'] as string;

  const { data: report, isLoading, refetch } = useReport(reportId);
  const shouldPoll = report?.status === 'GENERATING';
  const { data: statusData } = useReportStatus(reportId, shouldPoll);

  // Refresh full report when status transitions to READY
  React.useEffect(() => {
    if (statusData?.status === 'READY' && report?.status === 'GENERATING') {
      refetch();
    }
  }, [statusData?.status, report?.status, refetch]);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  if (!report) {
    return (
      <div className="py-20 text-center">
        <p className="text-muted-foreground">Không tìm thấy báo cáo.</p>
      </div>
    );
  }

  const sections = (report.content as { sections?: Record<string, ReportSection> })?.sections;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div className="flex items-start gap-3">
          <Link href="/dashboard/reports">
            <Button variant="ghost" size="sm" className="mt-1">
              <ArrowLeft className="h-4 w-4" />
            </Button>
          </Link>
          <div>
            <div className="flex items-center gap-2">
              <ReportTypeBadge type={report.type} />
              <ReportStatusBadge status={report.status} />
            </div>
            <h1 className="mt-1 text-xl font-bold">{report.title}</h1>
            <p className="text-xs text-muted-foreground">
              Tạo lúc {new Date(report.createdAt).toLocaleString('vi-VN')}
            </p>
          </div>
        </div>

        {report.status === 'READY' && (
          <div className="flex items-center gap-2">
            {report.pdfUrl && (
              <a href={report.pdfUrl} target="_blank" rel="noopener noreferrer">
                <Button variant="outline" size="sm">
                  <Download className="mr-1 h-4 w-4" />
                  PDF
                </Button>
              </a>
            )}
            <Button variant="outline" size="sm" onClick={() => window.print()}>
              <Printer className="mr-1 h-4 w-4" />
              In
            </Button>
          </div>
        )}
      </div>

      {/* Generating state */}
      {report.status === 'GENERATING' && (
        <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16">
          <Loader2 className="mb-4 h-10 w-10 animate-spin text-primary" />
          <h3 className="text-lg font-medium">Đang tạo báo cáo...</h3>
          <p className="mt-1 text-sm text-muted-foreground">
            Quá trình này có thể mất vài phút. Trang sẽ tự cập nhật khi hoàn thành.
          </p>
        </div>
      )}

      {/* Failed state */}
      {report.status === 'FAILED' && (
        <div className="rounded-lg border border-destructive/20 bg-destructive/5 p-6">
          <h3 className="font-medium text-destructive">Tạo báo cáo thất bại</h3>
          {report.errorMsg && (
            <p className="mt-1 text-sm text-destructive/80">{report.errorMsg}</p>
          )}
        </div>
      )}

      {/* Report content */}
      {report.status === 'READY' && sections && (
        <div className="grid gap-4 lg:grid-cols-[200px_1fr]">
          {/* Sidebar TOC */}
          <nav className="hidden lg:block">
            <p className="mb-2 text-xs font-semibold uppercase text-muted-foreground">Mục lục</p>
            <ul className="space-y-1">
              {Object.entries(sections).map(([key, section]) => (
                <li key={key}>
                  <a
                    href={`#section-${key}`}
                    className="block rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
                  >
                    {section.title}
                  </a>
                </li>
              ))}
            </ul>
          </nav>

          {/* Content sections */}
          <div className="space-y-4">
            {Object.entries(sections).map(([key, section]) => (
              <section
                key={key}
                id={`section-${key}`}
                className="rounded-lg border p-6"
              >
                <h2 className="mb-3 text-lg font-semibold">{section.title}</h2>
                {section.content && (
                  <div className="space-y-2 text-sm leading-relaxed text-muted-foreground whitespace-pre-line">
                    {String(section.content)}
                  </div>
                )}
                {section.charts && (
                  <ReportChartsGrid charts={section.charts as Record<string, Array<{ period: string; value: number; unit: string }>>} />
                )}
                {section.data != null && !section.charts && (
                  <ReportChartsGrid charts={section.data as Record<string, Array<{ period: string; value: number; unit: string }>>} />
                )}
                {section.projects && Array.isArray(section.projects) && section.projects.length > 0 && (
                  <div className="mt-3 overflow-x-auto">
                    <table className="w-full text-sm">
                      <thead>
                        <tr className="border-b text-left text-xs text-muted-foreground">
                          <th className="pb-2 pr-4">Tên</th>
                          <th className="pb-2 pr-4">Loại</th>
                          <th className="pb-2 pr-4">Trạng thái</th>
                        </tr>
                      </thead>
                      <tbody>
                        {section.projects.map((proj: unknown, i: number) => {
                          const p = proj as Record<string, unknown>;
                          return (
                            <tr key={i} className="border-b last:border-0">
                              <td className="py-2 pr-4 font-medium">{String(p['name'] ?? '')}</td>
                              <td className="py-2 pr-4">{String(p['category'] ?? '')}</td>
                              <td className="py-2 pr-4">{String(p['status'] ?? '')}</td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                )}
              </section>
            ))}
          </div>
        </div>
      )}

      {/* Raw JSON fallback for content without sections */}
      {report.status === 'READY' && !sections && report.content && (
        <pre className="max-h-[600px] overflow-auto rounded-lg border bg-muted p-4 text-xs">
          {JSON.stringify(report.content, null, 2)}
        </pre>
      )}
    </div>
  );
}
