"use client";

import { FileText, FileSpreadsheet } from "lucide-react";
import { trpc } from "@/trpc/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { LoadingState } from "@/components/shared/loading-state";
import { ErrorState } from "@/components/shared/error-state";
import { EmptyState } from "@/components/shared/empty-state";
import {
  type AnnualCategoryItem,
  type AnnualAwardItem,
  formatCurrency,
  formatDate,
  generateAnnualPDF,
  exportAnnualExcel,
} from "./export-utils";

export function AnnualSummarySection() {
  const {
    data: annual,
    isLoading: annualLoading,
    isError: annualError,
    error: annualQueryError,
  } = trpc.report.getAnnualSummary.useQuery(undefined);

  return (
    <>
      {annualLoading ? (
        <LoadingState />
      ) : annualError ? (
        <ErrorState message={annualQueryError?.message ?? "Failed to load annual summary"} />
      ) : !annual ? (
        <EmptyState title="No annual data" />
      ) : (
        <>
          <div className="mb-4 flex justify-end gap-2 print:hidden">
            <Button
              variant="outline"
              size="sm"
              onClick={() => generateAnnualPDF(annual)}
            >
              <FileText className="mr-2 h-4 w-4" />
              Export PDF
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => exportAnnualExcel(annual)}
            >
              <FileSpreadsheet className="mr-2 h-4 w-4" />
              Export Excel
            </Button>
          </div>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium">
                  Total Tenders
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">
                  {annual.totalTenders}
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium">
                  Total Value
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">
                  {formatCurrency(annual.totalValue)}
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium">
                  Total Budget
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">
                  {formatCurrency(annual.totalBudget)}
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium">
                  Budget Utilisation
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-primary text-2xl font-bold">
                  {annual.budgetUtilization}%
                </div>
              </CardContent>
            </Card>
          </div>

          <div className="mt-6 grid grid-cols-2 gap-4 lg:grid-cols-4">
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm">Draft</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-xl font-bold">
                  {annual.byStatus?.draft || 0}
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm">Published</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-xl font-bold">
                  {annual.byStatus?.published || 0}
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm">Awarded</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-xl font-bold text-green-600">
                  {annual.byStatus?.awarded || 0}
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm">Rejected</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-xl font-bold text-red-600">
                  {annual.byStatus?.rejected || 0}
                </div>
              </CardContent>
            </Card>
          </div>

          {annual.byCategory && annual.byCategory.length > 0 && (
            <Card className="mt-6">
              <CardHeader>
                <CardTitle>Category-wise Breakdown</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr className="border-b">
                        <th className="pb-3 text-left">Category</th>
                        <th className="pb-3 text-center">Code</th>
                        <th className="pb-3 text-center">Total Tenders</th>
                        <th className="pb-3 text-center">Awarded</th>
                        <th className="pb-3 text-right">Total Value</th>
                      </tr>
                    </thead>
                    <tbody>
                      {annual.byCategory.map((cat: AnnualCategoryItem, i: number) => (
                        <tr key={i} className="border-b">
                          <td className="py-3">{cat.category}</td>
                          <td className="text-muted-foreground py-3 text-center">
                            {cat.code}
                          </td>
                          <td className="py-3 text-center">
                            {cat.totalTenders}
                          </td>
                          <td className="py-3 text-center">
                            {cat.awardedTenders}
                          </td>
                          <td className="py-3 text-right">
                            {formatCurrency(cat.totalValue)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </CardContent>
            </Card>
          )}

          {annual.recentAwards && annual.recentAwards.length > 0 && (
            <Card className="mt-6">
              <CardHeader>
                <CardTitle>Recent Awards</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr className="border-b">
                        <th className="pb-3 text-left">Reference</th>
                        <th className="pb-3 text-left">Title</th>
                        <th className="pb-3 text-left">Category</th>
                        <th className="pb-3 text-left">Fiscal Year</th>
                        <th className="pb-3 text-left">Vendor</th>
                        <th className="pb-3 text-right">Amount</th>
                        <th className="pb-3 text-left">Date</th>
                      </tr>
                    </thead>
                    <tbody>
                      {annual.recentAwards.map((award: AnnualAwardItem) => (
                        <tr key={award.id} className="border-b">
                          <td className="py-3">{award.referenceNo}</td>
                          <td className="py-3">{award.title}</td>
                          <td className="text-muted-foreground py-3">
                            {award.category}
                          </td>
                          <td className="py-3">{award.fiscalYear}</td>
                          <td className="py-3">{award.vendor}</td>
                          <td className="py-3 text-right">
                            {formatCurrency(award.amount)}
                          </td>
                          <td className="py-3">
                            {formatDate(award.awardedAt)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </CardContent>
            </Card>
          )}
        </>
      )}
    </>
  );
}
