import {
  updatePaymentStatus,
  updateAcceptedTotal,
} from "@/app/admin/clients/[id]/actions";
import { initProjectPayments } from "@/app/admin/projects/project-actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { SplitPaymentForm } from "@/components/admin/SplitPaymentForm";
import type { Payment } from "@/db/schema";

type Props = {
  payments: Payment[];
  acceptedTotal: string;
  clientId: string;
  projectId?: string; // set only from project detail page — enables init & split
};

const statusLabels: Record<string, string> = {
  da_saldare: "Da saldare",
  inviata: "Inviata",
  saldato: "Saldato",
};

export async function PaymentsTab({ payments, acceptedTotal, clientId, projectId }: Props) {
  return (
    <div className="space-y-6 max-w-md">
      {/* Accepted total */}
      <div className="bg-white border border-gray-200 rounded-lg p-4">
        <h3 className="font-medium text-gray-900 mb-3">Totale preventivo</h3>
        <form
          action={async (fd: FormData) => {
            "use server";
            await updateAcceptedTotal(clientId, fd);
          }}
          className="flex items-end gap-3"
        >
          <div className="space-y-1 flex-1">
            <Label htmlFor="accepted_total">Importo (€)</Label>
            <Input
              id="accepted_total"
              name="accepted_total"
              type="number"
              step="0.01"
              min="0"
              defaultValue={acceptedTotal}
              className="max-w-xs"
            />
          </div>
          <Button type="submit" size="sm">
            Salva
          </Button>
        </form>
        <p className="text-xs text-gray-400 mt-2">
          Le rate Acconto e Saldo vengono aggiornate automaticamente al 50% ciascuna.
        </p>
      </div>

      {/* Empty state — project has no payments yet */}
      {projectId && payments.length === 0 && (
        <div className="bg-white border border-dashed border-gray-300 rounded-lg p-6 text-center">
          <p className="text-sm text-[#71717a] mb-4">
            Nessun pagamento configurato. Crea le rate standard Acconto e Saldo.
          </p>
          <form
            action={async () => {
              "use server";
              await initProjectPayments(projectId);
            }}
          >
            <Button type="submit" size="sm">
              Crea Acconto &amp; Saldo
            </Button>
          </form>
        </div>
      )}

      {/* Payment rows */}
      {payments.map((p) => {
        const amount = parseFloat(p.amount);
        return (
          <div
            key={p.id}
            className="bg-white border border-gray-200 rounded-lg p-4"
          >
            <div className="flex items-center justify-between mb-2">
              <h3 className="font-medium text-gray-900">{p.label}</h3>
              <div className="flex items-center gap-2">
                <span className="text-sm text-gray-600">
                  €{" "}
                  {amount.toLocaleString("it-IT", {
                    minimumFractionDigits: 2,
                  })}
                </span>
                {projectId && amount > 0 && (
                  <SplitPaymentForm
                    paymentId={p.id}
                    projectId={projectId}
                    currentAmount={amount}
                  />
                )}
              </div>
            </div>
            <form
              action={async (fd: FormData) => {
                "use server";
                await updatePaymentStatus(p.id, clientId, fd.get("status") as string);
              }}
              className="flex items-center gap-2"
            >
              <select
                name="status"
                defaultValue={p.status}
                className="text-sm border border-gray-200 rounded px-2 py-1.5 bg-white flex-1"
              >
                {Object.entries(statusLabels).map(([val, label]) => (
                  <option key={val} value={val}>
                    {label}
                  </option>
                ))}
              </select>
              <Button type="submit" size="sm" variant="outline">
                Aggiorna
              </Button>
            </form>
          </div>
        );
      })}
    </div>
  );
}