'use client';

import { FileText, Plus, X } from 'lucide-react';
import * as React from 'react';
import { ReportCard } from '@/components/reports/report-card';
import { REPORT_TYPES } from '@/components/reports/report-type-badge';
import { Button } from '@/components/ui/button';
import { Link } from '@/i18n/navigation';
import { useReportsList, useDeleteReport } from '@/lib/hooks/use-reports';
import type { ReportType } from '@/lib/reports-api';

const PAGE_SIZE = 12;

export default function BaoCaoPage() {
  const [typeFilter, setTypeFilter] = React.useState<ReportType | undefined>();
  const [page, setPage] = React.useState(1);

  const offset = (page - 1) * PAGE_SIZE;
  const { data, isLoading, isError } = useReportsList({
    type: typeFilter,
    limit: PAGE_SIZE,
    offset,
  });

  const deleteReport = useDeleteReport();

  const totalPages = data ? Math.ceil(data.total / PAGE_SIZE) : 0;

  const handleTypeChange = (type: ReportType | undefined) => {
    setTypeFilter(type);
    setPage(1);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handlePageChange = (newPage: number) => {
    setPage(newPage);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = (id: string) => {
    deleteReport.mutate(id);
  };

  return (
    <div className="mx-auto max-w-7xl px-4 py-6">
      {/* Page header */}
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold md:text-3xl">Báo cáo</h1>
          <p className="mt-1 text-muted-foreground">
            Quản lý và tạo báo cáo phân tích bất động sản
          </p>
        </div>
        <Link href="/bao-cao/tao-moi">
          <Button className="gap-2">
            <Plus className="h-4 w-4" />
            Tạo báo cáo mới
          </Button>
        </Link>
      </div>

      {/* Type filter tabs */}
      <div className="flex gap-1 overflow-x-auto border-b" role="tablist">
        <button
          role="tab"
          aria-selected={!typeFilter}
          className={`shrink-0 border-b-2 px-4 py-2 text-sm font-medium transition-colors ${
            !typeFilter
              ? 'border-primary text-primary'
              : 'border-transparent text-muted-foreground hover:text-foreground'
          }`}
          onClick={() => handleTypeChange(undefined)}
        >
          Tất cả
        </button>
        {REPORT_TYPES.map(({ value, label }) => (
          <button
            key={value}
            role="tab"
            aria-selected={typeFilter === value}
            className={`shrink-0 border-b-2 px-4 py-2 text-sm font-medium transition-colors ${
              typeFilter === value
                ? 'border-primary text-primary'
                : 'border-transparent text-muted-foreground hover:text-foreground'
            }`}
            onClick={() => handleTypeChange(value)}
          >
            {label}
          </button>
        ))}
        {typeFilter && (
          <button
            className="ml-auto shrink-0 px-2 py-2 text-sm text-muted-foreground hover:text-foreground"
            onClick={() => handleTypeChange(undefined)}
          >
            <X className="h-3.5 w-3.5" />
          </button>
        )}
      </div>

      {/* Results */}
      <div className="mt-6">
        {isLoading ? (
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {Array.from({ length: 6 }).map((_, i) => (
              <div key={i} className="h-32 animate-pulse rounded-lg bg-muted" />
            ))}
          </div>
        ) : isError ? (
          <div className="py-12 text-center">
            <p className="text-muted-foreground">
              Không thể tải danh sách báo cáo. Vui lòng thử lại.
            </p>
            <Button variant="outline" className="mt-4" onClick={() => setPage(page)}>
              Thử lại
            </Button>
          </div>
        ) : data && data.data.length > 0 ? (
          <>
            <p className="mb-4 text-sm text-muted-foreground">
              {data.total} báo cáo
            </p>

            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {data.data.map((report) => (
                <ReportCard key={report.id} report={report} onDelete={handleDelete} />
              ))}
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="mt-8 flex items-center justify-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  disabled={page === 1}
                  onClick={() => handlePageChange(page - 1)}
                >
                  Trước
                </Button>
                <span className="text-sm text-muted-foreground">
                  Trang {page} / {totalPages}
                </span>
                <Button
                  variant="outline"
                  size="sm"
                  disabled={page >= totalPages}
                  onClick={() => handlePageChange(page + 1)}
                >
                  Sau
                </Button>
              </div>
            )}
          </>
        ) : (
          <div className="py-12 text-center">
            <FileText className="mx-auto h-12 w-12 text-muted-foreground/30" />
            <p className="mt-4 text-lg font-medium">Chưa có báo cáo nào</p>
            <p className="mt-1 text-sm text-muted-foreground">
              Tạo báo cáo phân tích đầu tiên của bạn
            </p>
            <Link href="/bao-cao/tao-moi">
              <Button className="mt-4 gap-2">
                <Plus className="h-4 w-4" />
                Tạo báo cáo mới
              </Button>
            </Link>
          </div>
        )}
      </div>
    </div>
  );
}
