import { Metadata } from "next";
import { redirect } from "next/navigation";
import { getCurrentUser } from "@/lib/auth/user";
import { createAdminClient } from "@/lib/supabase/admin";
import { PropertyTransactionRow } from "@/types/database";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ShieldCheck, CheckCircle2, AlertTriangle, FileText, Clock, ExternalLink } from "lucide-react";
import { formatNaira, formatListingTimestamp } from "@/lib/utils";
import Link from "next/link";

export const metadata: Metadata = {
  title: "Deal Verification & Audit Desk | Nigeria Listing Admin",
};

export default async function AdminDealsPage() {
  const user = await getCurrentUser().catch(() => null);
  if (!user || (!user.roles.includes("SUPER_ADMIN") && !user.roles.includes("EMPLOYEE"))) {
    redirect("/dashboard");
  }

  const supabase = createAdminClient();
  const { data: transactions } = await supabase
    .from("property_transactions")
    .select(`
      *,
      property:properties!property_id(id, title, slug, reference_code, price, street_address),
      agent:users!agent_id(id, first_name, last_name, email, phone_number)
    `)
    .order("created_at", { ascending: false })
    .limit(50);

  const txList = (transactions as any[]) || [
    {
      id: "tx-demo-1",
      property: {
        title: "4-Bedroom Semi-Detached Duplex with BQ",
        slug: "4-bedroom-semi-detached-duplex-ikoyi",
        reference_code: "NG-SOLD-902",
        price: 260000000,
        street_address: "Bourdillon Road, Ikoyi, Lagos",
      },
      agent: { first_name: "Femi", last_name: "Adeyemi", email: "femi@apexluxury.ng" },
      transaction_type: "SALE",
      final_price: 260000000,
      verification_status: "VERIFIED_PLATFORM_DEAL",
      buyer_confirmed_at: "2026-02-10T14:30:00Z",
      is_anomaly_flagged: false,
      created_at: "2026-02-10T12:00:00Z",
    },
    {
      id: "tx-demo-2",
      property: {
        title: "1,200 SQM Prime Residential Land Plot",
        slug: "1200-sqm-prime-land-guzape-abuja",
        reference_code: "NG-SOLD-118",
        price: 195000000,
        street_address: "Guzape Diplomatic Zone, Abuja",
      },
      agent: { first_name: "Hajia Zainab", last_name: "Al-Hassan", email: "zainab@capitalcrest.ng" },
      transaction_type: "SALE",
      final_price: 195000000,
      verification_status: "VERIFIED_OFFLINE_DEAL",
      proof_document_type: "DEED_OF_ASSIGNMENT",
      is_anomaly_flagged: false,
      created_at: "2026-01-20T10:00:00Z",
    },
  ];

  const pendingAudit = txList.filter((t) => t.verification_status === "PENDING_STAFF_AUDIT").length;
  const platformVerified = txList.filter((t) => t.verification_status === "VERIFIED_PLATFORM_DEAL").length;
  const flaggedCount = txList.filter((t) => t.is_anomaly_flagged || t.verification_status === "DISPUTED_OR_FLAGGED").length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-4 border-b border-border">
        <div>
          <h1 className="text-xl font-bold tracking-tight text-foreground sm:text-2xl flex items-center gap-2">
            <ShieldCheck className="size-6 text-emerald-600" />
            <span>Deal Verification & Audit Desk</span>
          </h1>
          <p className="text-xs text-muted-foreground mt-0.5">
            Audit offline transaction proofs, resolve buyer disputes, and protect marketplace closed track records.
          </p>
        </div>
      </div>

      {/* Metrics Row */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <Card className="p-4 rounded-xl border-border bg-card">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground font-medium">Pending Proof Audit</p>
              <p className="text-2xl font-black text-foreground font-mono mt-1">{pendingAudit}</p>
            </div>
            <Clock className="size-8 text-amber-500/40" />
          </div>
        </Card>

        <Card className="p-4 rounded-xl border-border bg-card">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground font-medium">Platform Confirmed Deals</p>
              <p className="text-2xl font-black text-emerald-600 font-mono mt-1">{platformVerified}</p>
            </div>
            <CheckCircle2 className="size-8 text-emerald-500/40" />
          </div>
        </Card>

        <Card className="p-4 rounded-xl border-border bg-card">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground font-medium">Flagged Anomalies / Disputes</p>
              <p className="text-2xl font-black text-destructive font-mono mt-1">{flaggedCount}</p>
            </div>
            <AlertTriangle className="size-8 text-destructive/40" />
          </div>
        </Card>
      </div>

      {/* Transaction List Table */}
      <div className="rounded-2xl border border-border bg-card overflow-hidden shadow-xs">
        <div className="p-4 border-b border-border bg-muted/30">
          <h3 className="font-bold text-sm text-foreground">Recent Property Transaction Records</h3>
        </div>

        <div className="divide-y divide-border">
          {txList.map((tx) => {
            const agentName = tx.agent
              ? `${tx.agent.first_name || ""} ${tx.agent.last_name || ""}`.trim()
              : "Realtor";

            return (
              <div key={tx.id} className="p-4 sm:p-5 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div className="space-y-1.5 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="font-bold text-sm text-foreground truncate">
                      {tx.property?.title || "Property Deal"}
                    </span>
                    <Badge variant="outline" className="font-mono text-[10px]">
                      {tx.property?.reference_code || "REF"}
                    </Badge>
                  </div>

                  <p className="text-xs text-muted-foreground">
                    Agent: <strong className="text-foreground">{agentName}</strong> · Closed:{" "}
                    <span className="font-bold text-foreground">{formatNaira(tx.final_price || 0)}</span> ·{" "}
                    {formatListingTimestamp(tx.created_at)}
                  </p>

                  {tx.is_anomaly_flagged && (
                    <p className="text-xs text-destructive flex items-center gap-1 font-medium">
                      <AlertTriangle className="size-3.5 shrink-0" />
                      <span>{tx.anomaly_reason || "Automated anomaly detected"}</span>
                    </p>
                  )}
                </div>

                {/* Status Badge */}
                <div className="flex items-center gap-2 shrink-0">
                  {tx.verification_status === "VERIFIED_PLATFORM_DEAL" && (
                    <Badge className="bg-amber-500/15 text-amber-700 dark:text-amber-300 border-amber-500/30 text-xs font-bold gap-1">
                      <ShieldCheck className="size-3.5 text-amber-600" />
                      Buyer Confirmed
                    </Badge>
                  )}

                  {tx.verification_status === "VERIFIED_OFFLINE_DEAL" && (
                    <Badge className="bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 border-emerald-500/30 text-xs font-bold gap-1">
                      <CheckCircle2 className="size-3.5 text-emerald-600" />
                      Staff Audited
                    </Badge>
                  )}

                  {tx.verification_status === "PENDING_BUYER_CONFIRMATION" && (
                    <Badge variant="outline" className="text-amber-600 border-amber-500/30 text-xs gap-1">
                      <Clock className="size-3.5" />
                      Awaiting Buyer
                    </Badge>
                  )}

                  {tx.verification_status === "PENDING_STAFF_AUDIT" && (
                    <Badge className="bg-primary/10 text-primary border-primary/20 text-xs gap-1">
                      <FileText className="size-3.5" />
                      Review Proof
                    </Badge>
                  )}

                  {tx.verification_status === "DISPUTED_OR_FLAGGED" && (
                    <Badge variant="destructive" className="text-xs gap-1">
                      <AlertTriangle className="size-3.5" />
                      Disputed
                    </Badge>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
