import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { CreditCard, ArrowUpRight, Loader2 } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { formatDateTimeCompactEST } from "@/lib/timezoneUtils";

interface Transaction {
  id: string;
  amount: number;
  currency: string;
  status: string;
  created: number;
  description: string | null;
  customer_name: string | null;
  customer_email: string | null;
  payment_method: string | null;
}

interface Account {
  id: string;
  name: string;
  hasSecretKey: boolean;
}

export function StripeTransactionsCard() {
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [accounts, setAccounts] = useState<Account[]>([]);
  const AVRIA_MAPPING_ID = "04c535a6-51a1-49d0-bad0-3e0ea264cfa1";
  const [selectedAccount, setSelectedAccount] = useState<string>(AVRIA_MAPPING_ID);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchTransactions = async (mappingId?: string) => {
    setLoading(true);
    setError(null);
    try {
      const params: Record<string, string> = { limit: "3" };
      if (mappingId && mappingId !== "all") {
        params.mapping_id = mappingId;
      }

      const queryString = new URLSearchParams(params).toString();
      const { data: sessionData, error: sessionError } = await supabase.auth.getSession();
      const accessToken = sessionData.session?.access_token;

      if (sessionError || !accessToken) {
        setError("Please sign in as an admin or manager to view Stripe transactions.");
        setTransactions([]);
        return;
      }

      const res = await fetch(
        `${import.meta.env.VITE_SUPABASE_URL}/functions/v1/stripe-transactions?${queryString}`,
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );

      const result = await res.json().catch(() => ({}));

      if (!res.ok || result.error) {
        setError(result.error || `Unable to load Stripe transactions (${res.status})`);
        setTransactions([]);
        return;
      }

      setTransactions(result.transactions || []);
      if (result.accounts && accounts.length === 0) {
        setAccounts(result.accounts);
      }
    } catch (err: any) {
      setError(err.message || "Failed to load transactions");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTransactions(selectedAccount);
  }, [selectedAccount]);

  const formatAmount = (amount: number, currency: string) => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: currency.toUpperCase(),
    }).format(amount / 100);
  };

  const statusBadge = (status: string) => {
    const map: Record<string, string> = {
      succeeded: "cc-badge-success",
      pending: "cc-badge-warning",
      failed: "cc-badge-danger",
    };
    return (
      <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-2xs font-medium border ${map[status] || "cc-badge-neutral"}`}>
        {status}
      </span>
    );
  };

  return (
    <Card className="border shadow-sm">
      <CardHeader className="pb-2 px-4 pt-4">
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="text-[15px] font-semibold flex items-center gap-2">
              <CreditCard className="h-4 w-4 text-primary" /> Stripe Transactions
            </CardTitle>
            <CardDescription className="text-[12px]">Recent payment activity</CardDescription>
          </div>
          {accounts.length > 1 && (
            <Select value={selectedAccount} onValueChange={setSelectedAccount}>
              <SelectTrigger className="w-[200px] h-8 text-[12px]">
                <SelectValue placeholder="All accounts" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Accounts</SelectItem>
                {accounts.map((acc) => (
                  <SelectItem key={acc.id} value={acc.id}>
                    {acc.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          )}
        </div>
      </CardHeader>
      <CardContent className="px-0 pb-0">
        {loading ? (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
          </div>
        ) : error ? (
          <div className="text-center py-8 px-4">
            <p className="text-[13px] text-muted-foreground">{error}</p>
          </div>
        ) : transactions.length === 0 ? (
          <div className="text-center py-8 px-4">
            <CreditCard className="h-6 w-6 text-muted-foreground/20 mx-auto mb-2" />
            <p className="text-[13px] text-muted-foreground">No recent transactions</p>
          </div>
        ) : (
          <div className="divide-y divide-border">
            {transactions.map((tx) => (
              <div
                key={tx.id}
                className="flex items-center justify-between gap-3 px-4 py-2.5 hover:bg-muted/50 transition-colors"
              >
                <div className="min-w-0 flex-1">
                  <p className="text-[13px] font-medium text-foreground truncate">
                    {tx.customer_name || tx.customer_email || tx.description || "Payment"}
                  </p>
                  <div className="flex items-center gap-2 mt-0.5">
                    {statusBadge(tx.status)}
                    <span className="text-2xs text-muted-foreground">
                      {formatDateTimeCompactEST(new Date(tx.created * 1000))}
                    </span>
                  </div>
                </div>
                <span className="text-[14px] font-semibold text-foreground shrink-0">
                  {formatAmount(tx.amount, tx.currency)}
                </span>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
