'use client';

import { useState } from 'react';
import type { StoreMember } from '@alqove/api-client';
import { formatPrice } from '@alqove/shared';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { useCreatePayRate, useMemberPayRates } from '@/lib/queries/use-team';
import { apiErrorMessage } from '@/lib/api-error';

const cls = 'w-full rounded border border-forest/20 bg-white px-2 py-1.5 text-sm';

/**
 * Append-only pay-rate history (Port 00 §1). Reading needs pay.view, adding
 * needs pay.manage — both owner-only in v1. Rates are entered in dollars and
 * sent as integer cents.
 */
export function PayRateDialog({
  storeId,
  member,
  canManage,
  trigger,
}: {
  storeId: string;
  member: StoreMember;
  canManage: boolean;
  trigger: React.ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const [dollars, setDollars] = useState('');
  const [effectiveAt, setEffectiveAt] = useState('');

  const rates = useMemberPayRates(open ? storeId : null, open ? member.id : null);
  const create = useCreatePayRate();

  const cents = Math.round(Number(dollars) * 100);
  const valid = dollars.trim() !== '' && Number.isFinite(cents) && cents >= 0;

  const submit = () =>
    create.mutate(
      {
        storeId,
        membershipId: member.id,
        input: {
          hourly_rate_cents: cents,
          ...(effectiveAt ? { effective_at: new Date(effectiveAt).toISOString() } : {}),
        },
      },
      {
        onSuccess: () => {
          setDollars('');
          setEffectiveAt('');
        },
      },
    );

  const list = rates.data?.data ?? [];

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{trigger}</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Pay rate — {member.name ?? 'Team member'}</DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <div className="overflow-hidden rounded-md border border-forest/20">
            {rates.isLoading && (
              <div className="p-4 text-sm text-ink/60" data-testid="pay-loading">
                Loading…
              </div>
            )}
            {rates.isError && (
              <div className="p-4 text-sm text-terracotta" data-testid="pay-error">
                Failed to load pay history.
              </div>
            )}
            {!rates.isLoading && !rates.isError && list.length === 0 && (
              <div className="p-4 text-sm text-ink/60" data-testid="pay-empty">
                No pay rate set yet.
              </div>
            )}
            {list.length > 0 && (
              <table className="w-full text-sm">
                <thead className="bg-bone/60">
                  <tr>
                    <Th>Hourly rate</Th>
                    <Th>Effective</Th>
                  </tr>
                </thead>
                <tbody>
                  {list.map((r) => (
                    <tr key={r.id} className="border-t border-forest/10" data-testid={`pay-row-${r.id}`}>
                      <td className="px-4 py-2 font-medium text-ink">{formatPrice(r.hourly_rate_cents)}</td>
                      <td className="px-4 py-2 text-ink/70">
                        {new Date(r.effective_at).toLocaleDateString()}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>

          {canManage && (
            <div className="space-y-3">
              <p className="text-xs uppercase tracking-wide text-ink/60">Set a new rate</p>
              <div className="grid grid-cols-2 gap-3">
                <label className="flex flex-col gap-1 text-sm">
                  <span className="text-xs text-ink/60">Hourly rate ($)</span>
                  <input
                    data-testid="pay-amount"
                    type="number"
                    min="0"
                    step="0.01"
                    value={dollars}
                    onChange={(e) => setDollars(e.target.value)}
                    className={cls}
                    placeholder="18.50"
                  />
                </label>
                <label className="flex flex-col gap-1 text-sm">
                  <span className="text-xs text-ink/60">Effective from (optional)</span>
                  <input
                    data-testid="pay-effective"
                    type="date"
                    value={effectiveAt}
                    onChange={(e) => setEffectiveAt(e.target.value)}
                    className={cls}
                  />
                </label>
              </div>
              {create.isError && (
                <p className="text-sm text-terracotta" data-testid="pay-create-error">
                  {apiErrorMessage(create.error, 'Failed to set pay rate.')}
                </p>
              )}
            </div>
          )}
        </div>

        <DialogFooter>
          <button
            type="button"
            onClick={() => setOpen(false)}
            className="rounded px-3 py-1.5 text-sm text-ink/70 hover:bg-bone"
          >
            Close
          </button>
          {canManage && (
            <button
              type="button"
              data-testid="pay-submit"
              onClick={submit}
              disabled={create.isPending || !valid}
              className="rounded bg-forest px-3 py-1.5 text-sm font-semibold text-white hover:bg-forest/90 disabled:opacity-50"
            >
              {create.isPending ? 'Saving…' : 'Add rate'}
            </button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function Th({ children }: { children: React.ReactNode }) {
  return (
    <th className="px-4 py-2 text-left text-xs font-medium uppercase tracking-wide text-ink/60">
      {children}
    </th>
  );
}
