'use client';

import { useState } from 'react';
import { Pencil, Save, X, Settings2 } from 'lucide-react';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '../ui/card';

export interface WorkflowSettingsCardProps {
  /** Workflow identifier — passed through to {@link onSave} so the consumer can persist. */
  workflowId: string;
  /** Current workflow-level settings (arbitrary key/value map). */
  settings: Record<string, unknown>;
  /**
   * Persist edited settings. Supplied by the consumer (no API coupling here).
   * Rejecting the promise surfaces its message inline. When omitted the card
   * is read-only (the Edit affordance is hidden).
   */
  onSave?: (settings: Record<string, unknown>) => Promise<void>;
}

/** Well-known settings with labels and descriptions */
const KNOWN_FIELDS: {
  key: string;
  label: string;
  hint: string;
  type: 'number' | 'text';
}[] = [
  { key: 'timeout', label: 'Timeout', hint: 'seconds', type: 'number' },
  { key: 'maxRetries', label: 'Max Retries', hint: 'attempts', type: 'number' },
];

export function WorkflowSettingsCard({
  workflowId: _workflowId,
  settings,
  onSave,
}: WorkflowSettingsCardProps) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState<Record<string, unknown>>({ ...settings });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const knownKeys = new Set(KNOWN_FIELDS.map((f) => f.key));
  const unknownKeys = Object.keys(settings).filter((k) => !knownKeys.has(k));

  function handleEdit() {
    setDraft({ ...settings });
    setError(null);
    setEditing(true);
  }

  function handleCancel() {
    setDraft({ ...settings });
    setError(null);
    setEditing(false);
  }

  async function handleSave() {
    if (!onSave) return;
    setSaving(true);
    setError(null);
    try {
      await onSave(draft);
      setEditing(false);
    } catch (err) {
      setError(
        err instanceof Error ? err.message : 'Failed to save settings'
      );
    } finally {
      setSaving(false);
    }
  }

  function setField(key: string, value: unknown) {
    setDraft((prev) => ({ ...prev, [key]: value }));
  }

  const isEmpty = Object.keys(settings).length === 0;
  const canEdit = !!onSave;

  return (
    <Card>
      <CardHeader className="flex flex-row items-start justify-between space-y-0 pb-4">
        <div>
          <CardTitle className="flex items-center gap-2">
            <Settings2 className="h-5 w-5" />
            Settings
          </CardTitle>
          <CardDescription>Workflow-level configuration</CardDescription>
        </div>
        {!isEmpty &&
          canEdit &&
          (editing ? (
            <div className="flex items-center gap-2">
              <Button
                variant="ghost"
                size="sm"
                onClick={handleCancel}
                disabled={saving}
                className="gap-1.5"
              >
                <X className="h-3.5 w-3.5" />
                Cancel
              </Button>
              <Button
                size="sm"
                onClick={handleSave}
                disabled={saving}
                className="gap-1.5"
              >
                <Save className="h-3.5 w-3.5" />
                {saving ? 'Saving…' : 'Save'}
              </Button>
            </div>
          ) : (
            <Button
              variant="ghost"
              size="sm"
              onClick={handleEdit}
              className="gap-1.5"
            >
              <Pencil className="h-3.5 w-3.5" />
              Edit
            </Button>
          ))}
      </CardHeader>

      <CardContent className="space-y-4">
        {isEmpty ? (
          <p className="text-sm text-muted-foreground">
            No settings configured.
          </p>
        ) : (
          <>
            {/* Known fields */}
            {KNOWN_FIELDS.filter((f) => f.key in settings).map((field) => (
              <div key={field.key} className="space-y-1.5">
                <Label className="text-sm font-medium">{field.label}</Label>
                {editing ? (
                  <div className="flex items-center gap-2">
                    <Input
                      type={field.type}
                      value={(draft[field.key] as string | number) ?? ''}
                      onChange={(e) =>
                        setField(
                          field.key,
                          field.type === 'number'
                            ? Number(e.target.value)
                            : e.target.value
                        )
                      }
                      className="max-w-[160px]"
                    />
                    <span className="text-sm text-muted-foreground">
                      {field.hint}
                    </span>
                  </div>
                ) : (
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-mono bg-muted px-2.5 py-1 rounded">
                      {String(settings[field.key])}
                    </span>
                    <span className="text-xs text-muted-foreground">
                      {field.hint}
                    </span>
                  </div>
                )}
              </div>
            ))}

            {/* Unknown / arbitrary keys */}
            {unknownKeys.map((key) => (
              <div key={key} className="space-y-1.5">
                <Label className="text-sm font-medium font-mono">{key}</Label>
                {editing ? (
                  <Input
                    value={
                      typeof draft[key] === 'object'
                        ? JSON.stringify(draft[key])
                        : String(draft[key] ?? '')
                    }
                    onChange={(e) => setField(key, e.target.value)}
                    className="font-mono text-sm"
                  />
                ) : (
                  <span className="text-sm font-mono bg-muted px-2.5 py-1 rounded block w-fit">
                    {typeof settings[key] === 'object'
                      ? JSON.stringify(settings[key])
                      : String(settings[key])}
                  </span>
                )}
              </div>
            ))}

            {error && <p className="text-sm text-destructive">{error}</p>}
          </>
        )}
      </CardContent>
    </Card>
  );
}
