'use client';
import { formatErrorBanner } from '@/lib/api/toast-error';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/components/ui/sheet';
import { apiFetch } from '@/lib/api/client';

interface TagFormProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  tag?: { id: string; name: string; color: string } | null;
  onSuccess: () => void;
}

const PRESET_COLORS = [
  '#6B7280',
  '#EF4444',
  '#F97316',
  '#EAB308',
  '#22C55E',
  '#14B8A6',
  '#3B82F6',
  '#8B5CF6',
  '#EC4899',
  '#F43F5E',
];

export function TagForm({ open, onOpenChange, tag, onSuccess }: TagFormProps) {
  const [name, setName] = useState(tag?.name ?? '');
  const [color, setColor] = useState(tag?.color ?? '#6B7280');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isEdit = !!tag;

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      if (isEdit) {
        await apiFetch(`/api/v1/tags/${tag.id}`, {
          method: 'PATCH',
          body: { name, color },
        });
      } else {
        await apiFetch('/api/v1/tags', {
          method: 'POST',
          body: { name, color },
        });
      }
      onSuccess();
      onOpenChange(false);
    } catch (err: unknown) {
      const message = formatErrorBanner(err);
      setError(message);
    } finally {
      setLoading(false);
    }
  }

  function handleOpenChange(open: boolean) {
    if (!open) {
      setName(tag?.name ?? '');
      setColor(tag?.color ?? '#6B7280');
      setError(null);
    }
    onOpenChange(open);
  }

  return (
    <Sheet open={open} onOpenChange={handleOpenChange}>
      <SheetContent>
        <SheetHeader>
          <SheetTitle>{isEdit ? 'Edit Tag' : 'New Tag'}</SheetTitle>
        </SheetHeader>

        <form onSubmit={handleSubmit} className="mt-6 space-y-6">
          <div className="space-y-2">
            <Label htmlFor="tag-name">Name</Label>
            <Input
              id="tag-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g. VIP Client"
              maxLength={50}
              required
            />
          </div>

          <div className="space-y-2">
            <Label>Color</Label>
            <div className="flex flex-wrap gap-2">
              {PRESET_COLORS.map((c) => (
                <button
                  key={c}
                  type="button"
                  className="h-7 w-7 rounded-full ring-2 ring-offset-2 transition-all"
                  style={{
                    backgroundColor: c,
                    outline: color === c ? `2px solid ${c}` : '2px solid transparent',
                    outlineOffset: '2px',
                  }}
                  onClick={() => setColor(c)}
                  aria-label={`Select color ${c}`}
                />
              ))}
            </div>
            <div className="flex items-center gap-2 mt-2">
              {/* Native colour picker - clicking the swatch opens the
               *  OS picker, and the chosen colour writes back as a
               *  hex string. Keeps a manual hex input next to it for
               *  pasting brand colours from spec sheets. */}
              <input
                type="color"
                value={color}
                onChange={(e) => setColor(e.target.value)}
                className="h-7 w-7 rounded-full border cursor-pointer"
                aria-label="Pick custom color"
              />
              <Input
                value={color}
                onChange={(e) => setColor(e.target.value)}
                placeholder="#6B7280"
                className="w-28 font-mono text-sm h-9"
                maxLength={7}
              />
            </div>
          </div>

          {error && <p className="whitespace-pre-line text-sm text-destructive">{error}</p>}

          <SheetFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => handleOpenChange(false)}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={loading || !name.trim()}>
              {loading ? 'Saving…' : isEdit ? 'Save changes' : 'Create Tag'}
            </Button>
          </SheetFooter>
        </form>
      </SheetContent>
    </Sheet>
  );
}
