"use client";

import { useState } from "react";
import { Plus, Users, CheckCircle, Building2, Trophy, Clock } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { ChitFundDialog } from "@/components/chit-funds/ChitFundDialog";
import {
  useChitFunds,
  useDeleteChitFund,
  useMarkContributionPaid,
  type ChitFundWithRelations,
} from "@/hooks/use-chit-funds";
import { formatCents, formatDate } from "@/lib/utils/format";
import type { ChitContribution } from "@prisma/client";

const PERIOD_LABELS: Record<string, string> = {
  MONTHLY:  "month",
  BIWEEKLY: "2 weeks",
  WEEKLY:   "week",
};

function ChitFundCard({ fund }: { fund: ChitFundWithRelations }) {
  const deleteFund = useDeleteChitFund();
  const markPaid   = useMarkContributionPaid();

  const contributions  = fund.contributions as ChitContribution[];
  const total          = contributions.length;
  const paidCount      = contributions.filter((c) => c.isPaid).length;
  const progress       = total > 0 ? (paidCount / total) * 100 : 0;
  const payoutReceived = !!fund.receivedAt;

  // Next unpaid contribution
  const nextContrib = contributions.find((c) => !c.isPaid);

  // My turn contribution
  const myTurnContrib = fund.myTurnNumber
    ? contributions.find((c) => c.periodNumber === fund.myTurnNumber)
    : null;

  const totalPaidCents   = paidCount * fund.contributionCents;
  const totalExpectedCents = total * fund.contributionCents;
  const netPositionCents   = payoutReceived && fund.myPayoutCents
    ? fund.myPayoutCents - totalPaidCents
    : (fund.myPayoutCents ?? fund.chitValueCents) - totalExpectedCents;

  const isCompleted = fund.status === "COMPLETED" || paidCount === total;

  return (
    <Card className="bg-slate-800/50 border-slate-700/50">
      <CardContent className="p-4 space-y-3">

        {/* Header */}
        <div className="flex items-start justify-between">
          <div>
            <div className="flex items-center gap-2 flex-wrap">
              <Users className="h-4 w-4 text-violet-400 shrink-0" />
              <span className="font-semibold text-white">{fund.name}</span>
              {isCompleted ? (
                <Badge className="bg-emerald-900/50 text-emerald-400 border-emerald-700/50 text-xs">Completed</Badge>
              ) : (
                <Badge className="bg-violet-900/40 text-violet-300 border-violet-700/40 text-xs">Active</Badge>
              )}
            </div>
            {fund.organizer && (
              <p className="text-xs text-slate-500 mt-0.5">Organizer: {fund.organizer}</p>
            )}
          </div>
          <button
            onClick={() => {
              if (confirm("Remove this chit fund?")) deleteFund.mutate(fund.id);
            }}
            className="text-xs text-slate-600 hover:text-red-400 transition-colors shrink-0"
          >
            Remove
          </button>
        </div>

        {/* Linked account */}
        {fund.bankAccount && (
          <div className="flex items-center gap-1.5">
            <Building2 className="h-3 w-3 text-slate-500" />
            <span className="text-xs text-slate-500">Linked to</span>
            <span
              className="text-xs font-semibold px-2 py-0.5 rounded-full"
              style={{
                color:           fund.bankAccount.color ?? "#a78bfa",
                backgroundColor: `${fund.bankAccount.color ?? "#7c3aed"}20`,
              }}
            >
              {fund.bankAccount.name}
            </span>
          </div>
        )}

        {/* Stats grid */}
        <div className="grid grid-cols-3 gap-2 text-center">
          <div className="bg-slate-900/50 rounded-lg p-2">
            <div className="text-xs text-slate-400">Members</div>
            <div className="text-sm font-semibold text-white mt-0.5">{fund.totalMembers}</div>
          </div>
          <div className="bg-slate-900/50 rounded-lg p-2">
            <div className="text-xs text-slate-400">Per {PERIOD_LABELS[fund.periodType]}</div>
            <div className="text-sm font-semibold text-violet-300 mt-0.5">
              {formatCents(fund.contributionCents, fund.currency)}
            </div>
          </div>
          <div className="bg-slate-900/50 rounded-lg p-2">
            <div className="text-xs text-slate-400">Pot value</div>
            <div className="text-sm font-semibold text-emerald-400 mt-0.5">
              {formatCents(fund.chitValueCents, fund.currency)}
            </div>
          </div>
        </div>

        {/* Progress */}
        <div className="space-y-1">
          <div className="flex justify-between text-xs text-slate-400">
            <span>{paidCount} of {total} contributions paid</span>
            <span>{progress.toFixed(0)}%</span>
          </div>
          <Progress value={progress} className="h-1.5 bg-slate-700" />
        </div>

        {/* My turn info */}
        {myTurnContrib && (
          <div className={`rounded-lg px-3 py-2 flex items-center justify-between ${
            payoutReceived
              ? "bg-emerald-900/20 border border-emerald-700/30"
              : myTurnContrib.periodNumber <= paidCount + 1
              ? "bg-amber-900/20 border border-amber-700/30"
              : "bg-violet-900/15 border border-violet-700/30"
          }`}>
            <div className="flex items-center gap-2">
              <Trophy className={`h-3.5 w-3.5 shrink-0 ${payoutReceived ? "text-emerald-400" : "text-amber-400"}`} />
              <div>
                <p className="text-xs font-medium text-slate-200">
                  {payoutReceived ? "Payout received" : `Your turn: Period #${fund.myTurnNumber}`}
                </p>
                <p className="text-[10px] text-slate-500">
                  {payoutReceived
                    ? formatDate(fund.receivedAt!)
                    : `Due ${formatDate(myTurnContrib.dueDate)}`}
                </p>
              </div>
            </div>
            <div className="text-right">
              <p className="text-sm font-semibold text-emerald-400">
                {formatCents(fund.myPayoutCents ?? fund.chitValueCents, fund.currency)}
              </p>
              {!payoutReceived && myTurnContrib.periodNumber === (paidCount + 1) && (
                <button
                  onClick={() => markPaid.mutate({ chitFundId: fund.id, contribId: myTurnContrib.id, isPayout: true })}
                  disabled={markPaid.isPending}
                  className="mt-1 text-[10px] px-2 py-0.5 rounded bg-emerald-600/30 text-emerald-300 border border-emerald-600/40 hover:bg-emerald-600/50 transition-colors disabled:opacity-50"
                >
                  Mark received
                </button>
              )}
            </div>
          </div>
        )}

        {/* Net position */}
        <div className="flex items-center justify-between text-xs">
          <span className="text-slate-500">Net position</span>
          <span className={netPositionCents >= 0 ? "text-emerald-400 font-semibold" : "text-rose-400 font-semibold"}>
            {netPositionCents >= 0 ? "+" : ""}{formatCents(netPositionCents, fund.currency)}
          </span>
        </div>

        {/* Next contribution */}
        {nextContrib && !isCompleted && (
          <div className="flex items-center justify-between bg-slate-900/40 rounded-lg px-3 py-2">
            <div className="flex items-center gap-2">
              <Clock className="h-3.5 w-3.5 text-slate-500" />
              <div>
                <p className="text-xs text-slate-400">
                  Next · Period #{nextContrib.periodNumber} · {formatDate(nextContrib.dueDate)}
                </p>
                {fund.bankAccount && (
                  <p className="text-[10px] text-slate-600 mt-0.5">debits {fund.bankAccount.name}</p>
                )}
              </div>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-white font-medium text-sm">
                {formatCents(nextContrib.amountCents, fund.currency)}
              </span>
              <button
                onClick={() => markPaid.mutate({ chitFundId: fund.id, contribId: nextContrib.id })}
                disabled={markPaid.isPending}
                className="px-2.5 py-1 text-[11px] font-semibold rounded-lg bg-violet-600/20 text-violet-300 border border-violet-600/30 hover:bg-violet-600/30 transition-colors disabled:opacity-50"
              >
                {markPaid.isPending ? "…" : "Pay"}
              </button>
            </div>
          </div>
        )}

        {/* Completed state */}
        {isCompleted && (
          <div className="flex items-center gap-2 bg-emerald-900/20 rounded-lg px-3 py-2">
            <CheckCircle className="h-4 w-4 text-emerald-500" />
            <span className="text-xs text-emerald-400 font-medium">All contributions complete!</span>
          </div>
        )}

      </CardContent>
    </Card>
  );
}

export default function ChitFundsPage() {
  const { data: funds, isLoading } = useChitFunds();
  const [dialogOpen, setDialogOpen] = useState(false);

  const totalExpected = funds?.reduce((s, f) => s + f.chitValueCents, 0) ?? 0;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Chit Funds / ROSCA</h1>
          {funds && funds.length > 0 && (
            <p className="text-slate-400 text-sm mt-1">
              {funds.length} active group{funds.length > 1 ? "s" : ""} · {formatCents(totalExpected)} total pot value
            </p>
          )}
        </div>
        <Button
          onClick={() => setDialogOpen(true)}
          className="bg-violet-600 hover:bg-violet-500 text-white"
        >
          <Plus className="h-4 w-4 mr-2" />
          Add Chit Fund
        </Button>
      </div>

      {isLoading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {[1, 2].map((i) => (
            <div key={i} className="h-64 bg-slate-800/30 rounded-xl animate-pulse" />
          ))}
        </div>
      ) : !funds || funds.length === 0 ? (
        <Card className="bg-slate-800/30 border-slate-700/50 border-dashed">
          <CardContent className="flex flex-col items-center justify-center py-16 text-center">
            <Users className="h-10 w-10 text-slate-600 mb-3" />
            <p className="text-slate-400 font-medium">No chit funds yet</p>
            <p className="text-slate-500 text-sm mt-1 max-w-xs">
              Track your rotating savings groups — contributions, payouts and net position all in one place
            </p>
            <Button
              onClick={() => setDialogOpen(true)}
              className="mt-4 bg-violet-600 hover:bg-violet-500 text-white"
            >
              <Plus className="h-4 w-4 mr-2" />
              Add Chit Fund
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {funds.map((fund) => (
            <ChitFundCard key={fund.id} fund={fund} />
          ))}
        </div>
      )}

      <ChitFundDialog open={dialogOpen} onOpenChange={setDialogOpen} />
    </div>
  );
}
