'use client';

import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { Check, X } from 'lucide-react';
import { listBranches, type Branch } from '@client/api/branches';
import {
  listMenuItemBranches,
  setMenuItemBranchAvailability,
  clearMenuItemBranchAvailability,
} from '@client/api/menu';

interface Override {
  menu_item_id: string;
  branch_id: string;
  is_available: boolean;
  branch_name?: string;
}

interface Props {
  itemId: string;
  pinnedBranchId: string | null;
}

/**
 * Mini-control: per-branch availability override for a menu item.
 *
 * - Owners see one row per branch in the restaurant. Default state is
 *   "Inherit" (no override) — explicit on/off toggles persist into
 *   menu_item_branch_availability via PUT/DELETE.
 * - Pinned-branch operators only see + can mutate their own branch row
 *   (server enforces the same rule via assertBranchAccess).
 */
export default function BranchAvailability({ itemId, pinnedBranchId }: Props) {
  const [branches, setBranches] = useState<Branch[]>([]);
  const [overrides, setOverrides] = useState<Map<string, boolean>>(new Map());
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      try {
        const [branchRes, overrideRes] = await Promise.all([
          listBranches(),
          listMenuItemBranches(itemId) as Promise<{ overrides: Override[] }>,
        ]);
        if (cancelled) return;
        setBranches(branchRes.branches ?? []);
        const map = new Map<string, boolean>();
        for (const o of overrideRes.overrides ?? []) {
          map.set(o.branch_id, o.is_available);
        }
        setOverrides(map);
      } catch (err) {
        if (!cancelled) toast.error(err instanceof Error ? err.message : 'Failed to load branches');
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [itemId]);

  const handleSet = async (branchId: string, value: boolean | null) => {
    setBusy(branchId);
    try {
      if (value === null) {
        await clearMenuItemBranchAvailability(itemId, branchId);
        setOverrides(prev => { const m = new Map(prev); m.delete(branchId); return m; });
      } else {
        await setMenuItemBranchAvailability(itemId, branchId, value);
        setOverrides(prev => { const m = new Map(prev); m.set(branchId, value); return m; });
      }
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to update');
    } finally {
      setBusy(null);
    }
  };

  const visible = pinnedBranchId
    ? branches.filter(b => b.id === pinnedBranchId)
    : branches;

  if (loading) {
    return <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Loading branches…</p>;
  }
  if (visible.length === 0) {
    return <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>No branches configured.</p>;
  }

  return (
    <div className="space-y-2">
      <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
        Override item availability per branch. Inherit means follow the global is_available flag.
      </p>
      {visible.map(b => {
        const state = overrides.has(b.id) ? overrides.get(b.id)! : null;
        const disabled = busy === b.id;
        return (
          <div key={b.id} className="flex items-center gap-2 px-3 py-2 rounded-lg" style={{ backgroundColor: 'hsl(var(--muted))' }}>
            <span className="flex-1 text-sm font-medium truncate" style={{ color: 'hsl(var(--foreground))' }}>{b.name}</span>
            <div className="flex gap-1">
              <button
                type="button"
                disabled={disabled}
                onClick={() => handleSet(b.id, true)}
                className="px-2 py-1 rounded-md text-xs font-medium border transition-colors flex items-center gap-1"
                style={{
                  borderColor: state === true ? 'hsl(var(--success))' : 'hsl(var(--border))',
                  backgroundColor: state === true ? 'hsl(var(--success))' : 'transparent',
                  color: state === true ? 'white' : 'hsl(var(--muted-foreground))',
                  opacity: disabled ? 0.5 : 1,
                }}
                title="Available at this branch"
              >
                <Check size={11} /> On
              </button>
              <button
                type="button"
                disabled={disabled}
                onClick={() => handleSet(b.id, false)}
                className="px-2 py-1 rounded-md text-xs font-medium border transition-colors flex items-center gap-1"
                style={{
                  borderColor: state === false ? 'hsl(var(--danger))' : 'hsl(var(--border))',
                  backgroundColor: state === false ? 'hsl(var(--danger))' : 'transparent',
                  color: state === false ? 'white' : 'hsl(var(--muted-foreground))',
                  opacity: disabled ? 0.5 : 1,
                }}
                title="Hidden at this branch"
              >
                <X size={11} /> Off
              </button>
              <button
                type="button"
                disabled={disabled || state === null}
                onClick={() => handleSet(b.id, null)}
                className="px-2 py-1 rounded-md text-xs font-medium border transition-colors"
                style={{
                  borderColor: state === null ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                  backgroundColor: state === null ? 'hsl(var(--primary-light))' : 'transparent',
                  color: state === null ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))',
                  opacity: disabled || state === null ? 0.5 : 1,
                }}
                title="Inherit (no override)"
              >
                Inherit
              </button>
            </div>
          </div>
        );
      })}
    </div>
  );
}
