'use client';

import { animate, useReducedMotion } from 'framer-motion';
import { Calculator, Plus, Trash2, X } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';

import { FormField } from '@/components/forms/form-field';
import { PageHeader } from '@/components/layout/page-header';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Input } from '@/components/ui/input';
import { Menu } from '@/components/ui/menu';
import { Drawer } from '@/components/ui/overlay';
import { Segmented } from '@/components/ui/segmented';
import { EmptyState, ErrorState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { Switch } from '@/components/ui/switch';
import { ApiError, api } from '@/lib/api-client';
import { formatMoney, minorFromMajor } from '@/lib/money';
import { cn } from '@/lib/utils';

interface Rule {
  id: string;
  tenantId: string | null;
  tenantName: string | null;
  courierId: string | null;
  type: 'PERCENT' | 'FLAT';
  value: number;
  priority: number;
  active: boolean;
}

function AnimatedMoney({ minor }: { minor: number }) {
  const reduce = useReducedMotion();
  const [display, setDisplay] = useState(minor);
  const previous = useRef(minor);
  useEffect(() => {
    const from = previous.current;
    previous.current = minor;
    const controls = animate(from, minor, { duration: reduce ? 0 : 0.35, onUpdate: (latest) => setDisplay(Math.round(latest)) });
    return () => controls.stop();
  }, [minor, reduce]);
  return <span className="tabular-nums">{formatMoney(display, 'USD')}</span>;
}

export default function AdminPricingPage() {
  const queryClient = useQueryClient();
  const [type, setType] = useState<'PERCENT' | 'FLAT'>('PERCENT');
  const [value, setValue] = useState('10');
  const [priority, setPriority] = useState('0');
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<Rule | null>(null);
  const [previewTenantId, setPreviewTenantId] = useState('');
  const [previewCourierId, setPreviewCourierId] = useState('');
  const [previewBase, setPreviewBase] = useState('20');
  const [preview, setPreview] = useState<{ markupMinor: number; totalMinor: number; baseMinor: number } | null>(null);
  const [previewing, setPreviewing] = useState(false);

  const rules = useQuery({
    queryKey: ['admin', 'pricing'],
    queryFn: () => api<Rule[]>('/admin/pricing-rules'),
  });
  const rows = Array.isArray(rules.data) ? rules.data : [];
  const activeRules = rows.filter((rule) => rule.active);
  // Highlight the rule the preview most likely matched (most specific scope, then highest priority).
  const matched =
    preview === null
      ? null
      : ([...activeRules]
          .filter((rule) => (rule.tenantId === null || rule.tenantId === previewTenantId) && (rule.courierId === null || rule.courierId === previewCourierId))
          .sort((left, right) => Number(right.tenantId !== null) - Number(left.tenantId !== null) || Number(right.courierId !== null) - Number(left.courierId !== null) || right.priority - left.priority)[0] ?? null);

  return (
    <div className="grid gap-6">
      <PageHeader
        title="Pricing"
        description="Markup rules applied on top of courier cost."
        actions={
          <Button type="button" onClick={() => setDrawerOpen(true)}>
            <Plus className="h-4 w-4" aria-hidden="true" />
            Add rule
          </Button>
        }
      />
      <div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_340px] xl:items-start">
        <div>
          {rules.isLoading ? <Skeleton className="h-64 rounded-xl" /> : null}
          {rules.error instanceof ApiError ? (
            <Card>
              <ErrorState message={rules.error.message} requestId={rules.error.requestId} onRetry={() => void rules.refetch()} />
            </Card>
          ) : null}
          {rules.data !== undefined && rows.length === 0 ? (
            <Card>
              <EmptyState title="No pricing rules yet" description="The default markup from platform settings applies until you add a rule." />
            </Card>
          ) : null}
          {rows.length > 0 ? (
            <Card className="overflow-hidden p-0">
              <div className="overflow-x-auto">
                <table className="w-full min-w-[680px] text-left text-small">
                  <thead>
                    <tr className="h-11 border-b border-border bg-surface-muted/80 text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                      <th scope="col" className="pl-5 pr-3 font-semibold">Scope</th>
                      <th scope="col" className="px-3 font-semibold">Courier</th>
                      <th scope="col" className="px-3 font-semibold">Type</th>
                      <th scope="col" className="px-3 text-right font-semibold">Value</th>
                      <th scope="col" className="px-3 text-right font-semibold">Priority</th>
                      <th scope="col" className="px-3 font-semibold">Active</th>
                      <th scope="col" className="w-12 pr-3">
                        <span className="sr-only">Actions</span>
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {rows.map((rule) => (
                      <tr key={rule.id} className={cn('h-14 border-b border-border transition-colors last:border-b-0', matched?.id === rule.id && 'bg-primary-soft')}>
                        <td className="pl-5 pr-3 font-semibold">{rule.tenantName ?? <span className="text-muted-foreground">Global</span>}</td>
                        <td className="px-3 font-mono text-caption">{rule.courierId ?? <span className="font-sans text-small text-muted-foreground">Any</span>}</td>
                        <td className="px-3">
                          <span className={cn('rounded-pill px-2.5 py-0.5 text-caption font-semibold', rule.type === 'PERCENT' ? 'bg-primary-soft text-primary' : 'bg-info-soft text-info')}>
                            {rule.type === 'PERCENT' ? 'Percent' : 'Flat'}
                          </span>
                        </td>
                        <td className="px-3 text-right font-semibold tabular-nums">{rule.type === 'PERCENT' ? `${rule.value}%` : rule.value}</td>
                        <td className="px-3 text-right tabular-nums text-muted-foreground">{rule.priority}</td>
                        <td className="px-3">
                          <Switch
                            checked={rule.active}
                            onCheckedChange={(checked) => {
                              void api(`/admin/pricing-rules/${rule.id}`, { method: 'PATCH', json: { active: checked } })
                                .then(async () => {
                                  await queryClient.invalidateQueries({ queryKey: ['admin', 'pricing'] });
                                })
                                .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'Update failed.'));
                            }}
                            label={`Rule ${rule.tenantName ?? 'global'} active`}
                          />
                        </td>
                        <td className="pr-3">
                          <Menu items={[{ label: 'Delete rule', icon: Trash2, danger: true, onSelect: () => setDeleteTarget(rule) }]} label="Rule actions" />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </Card>
          ) : null}
        </div>

        <Card className="p-5 xl:sticky xl:top-24">
          <h2 className="flex items-center gap-2 font-display text-h3 font-bold">
            <Calculator className="h-[18px] w-[18px] text-primary" aria-hidden="true" />
            Preview calculator
          </h2>
          <form
            className="mt-4 grid gap-3"
            onSubmit={(event) => {
              event.preventDefault();
              const baseMinor = minorFromMajor(previewBase);
              if (baseMinor === null) {
                toast.error('Enter a valid base amount.');
                return;
              }
              setPreviewing(true);
              void api<{ baseMinor: number; markupMinor: number; totalMinor: number }>('/admin/pricing-preview', {
                method: 'POST',
                json: { tenantId: previewTenantId, courierId: previewCourierId, baseMinor },
              })
                .then(setPreview)
                .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'Preview failed.'))
                .finally(() => setPreviewing(false));
            }}
          >
            <FormField id="preview-tenant" label="Tenant ID">
              <Input id="preview-tenant" className="font-mono text-small" value={previewTenantId} onChange={(event) => setPreviewTenantId(event.target.value)} />
            </FormField>
            <FormField id="preview-courier" label="Courier ID">
              <Input id="preview-courier" className="font-mono text-small" value={previewCourierId} onChange={(event) => setPreviewCourierId(event.target.value)} />
            </FormField>
            <FormField id="preview-base" label="Base amount">
              <Input id="preview-base" inputMode="decimal" className="tabular-nums" leading={<span className="text-small font-semibold text-muted-foreground">USD</span>} value={previewBase} onChange={(event) => setPreviewBase(event.target.value)} />
            </FormField>
            <Button type="submit" variant="secondary" loading={previewing}>
              Calculate
            </Button>
          </form>
          {preview === null ? null : (
            <dl className="mt-4 grid gap-2 rounded-lg bg-surface-muted p-4 text-small" aria-live="polite">
              <div className="flex justify-between">
                <dt className="text-muted-foreground">Base</dt>
                <dd>
                  <AnimatedMoney minor={preview.baseMinor} />
                </dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-muted-foreground">Markup</dt>
                <dd className="text-primary">
                  + <AnimatedMoney minor={preview.markupMinor} />
                </dd>
              </div>
              <div className="flex items-end justify-between border-t border-dashed border-border-strong pt-2">
                <dt className="font-semibold">Total</dt>
                <dd className="font-display text-h2 font-extrabold">
                  <AnimatedMoney minor={preview.totalMinor} />
                </dd>
              </div>
              {matched === null ? null : <p className="mt-1 text-caption text-muted-foreground">Likely matched rule is highlighted in the table.</p>}
            </dl>
          )}
        </Card>
      </div>

      <Drawer open={drawerOpen} title="Add pricing rule" side="right" onClose={() => setDrawerOpen(false)} className="flex flex-col p-0">
        <div className="flex items-center justify-between border-b border-border px-6 py-4">
          <h2 className="font-display text-h3 font-bold">Add pricing rule</h2>
          <button type="button" aria-label="Close" onClick={() => setDrawerOpen(false)} className="grid h-9 w-9 place-items-center rounded-md text-muted-foreground hover:bg-surface-muted hover:text-foreground">
            <X className="h-4 w-4" aria-hidden="true" />
          </button>
        </div>
        <form
          className="flex min-h-0 flex-1 flex-col"
          onSubmit={(event) => {
            event.preventDefault();
            void api('/admin/pricing-rules', {
              method: 'POST',
              json: { type, value: Number(value), priority: Number(priority), active: true },
            })
              .then(async () => {
                toast.success('Rule created.');
                setDrawerOpen(false);
                await queryClient.invalidateQueries({ queryKey: ['admin', 'pricing'] });
              })
              .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'Create failed.'));
          }}
        >
          <div className="grid flex-1 content-start gap-4 overflow-y-auto px-6 py-5">
            <div className="grid gap-1.5">
              <span className="text-small font-semibold">Type</span>
              <Segmented<'PERCENT' | 'FLAT'>
                label="Rule type"
                value={type}
                onChange={setType}
                options={[
                  { value: 'PERCENT', label: 'Percent' },
                  { value: 'FLAT', label: 'Flat' },
                ]}
                className="w-fit"
              />
            </div>
            <FormField id="rule-value" label={type === 'PERCENT' ? 'Markup percent' : 'Flat markup (minor units)'}>
              <Input id="rule-value" inputMode="decimal" className="tabular-nums" value={value} onChange={(event) => setValue(event.target.value)} />
            </FormField>
            <FormField id="rule-priority" label="Priority" hint="Higher priority wins when several rules match.">
              <Input id="rule-priority" inputMode="numeric" className="tabular-nums" value={priority} aria-describedby="rule-priority-hint" onChange={(event) => setPriority(event.target.value)} />
            </FormField>
            <p className="rounded-lg bg-surface-muted px-3 py-2 text-caption text-muted-foreground">New rules apply globally to all tenants and couriers.</p>
          </div>
          <div className="flex justify-end gap-2 border-t border-border px-6 py-4">
            <Button type="button" variant="secondary" onClick={() => setDrawerOpen(false)}>
              Cancel
            </Button>
            <Button type="submit">Create rule</Button>
          </div>
        </form>
      </Drawer>

      <ConfirmDialog
        open={deleteTarget !== null}
        title="Delete this pricing rule?"
        message="New quotes stop using this markup immediately. Existing shipments keep their price."
        confirmLabel="Delete rule"
        cancelLabel="Keep rule"
        onClose={() => setDeleteTarget(null)}
        onConfirm={() => {
          if (deleteTarget === null) return;
          const target = deleteTarget;
          setDeleteTarget(null);
          void api(`/admin/pricing-rules/${target.id}`, { method: 'DELETE' })
            .then(async () => {
              toast.success('Rule deleted.');
              await queryClient.invalidateQueries({ queryKey: ['admin', 'pricing'] });
            })
            .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'Delete failed.'));
        }}
      />
    </div>
  );
}
