import { useState } from 'react';
import { Check, KeyRound, Loader2, AlertCircle } from 'lucide-react';
import { authFetch } from '../../lib/auth';

export interface EnvField {
  name: string;
  label: string;
  placeholder: string;
}

export interface EnvGroupData {
  title: string;
  fields: EnvField[];
}

interface Props {
  group: EnvGroupData;
}

export default function EnvForm({ group }: Props) {
  const [values, setValues] = useState<Record<string, string>>({});
  const [status, setStatus] = useState<'idle' | 'submitting' | 'submitted' | 'error'>('idle');
  const [errorMsg, setErrorMsg] = useState('');

  const handleChange = (name: string, value: string) => {
    setValues((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async () => {
    // Check that at least one field has a value
    const filled = Object.entries(values).filter(([, v]) => v.trim());
    if (filled.length === 0) return;

    setStatus('submitting');
    setErrorMsg('');

    try {
      const res = await authFetch('/api/env', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ vars: Object.fromEntries(filled) }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({ error: 'Request failed' }));
        throw new Error(data.error || 'Request failed');
      }
      setStatus('submitted');
    } catch (err: any) {
      setErrorMsg(err.message || 'Failed to save');
      setStatus('error');
    }
  };

  const filledCount = Object.values(values).filter((v) => v.trim()).length;

  // Submitted state
  if (status === 'submitted') {
    return (
      <div className="my-3 rounded-xl border border-emerald-500/20 bg-emerald-500/5 overflow-hidden">
        <div className="flex items-center gap-3 px-4 py-3">
          <div className="flex items-center justify-center w-8 h-8 rounded-lg bg-emerald-500 shrink-0">
            <Check className="w-4 h-4 text-white" strokeWidth={3} />
          </div>
          <div className="flex flex-col min-w-0">
            <span className="text-emerald-400 font-medium text-sm">{group.title}</span>
            <span className="text-muted-foreground text-xs">
              {filledCount} variable{filledCount !== 1 ? 's' : ''} saved — backend restarting
            </span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="my-3 rounded-xl border border-border/60 bg-card/50 overflow-hidden">
      {/* Header */}
      <div className="flex items-center gap-2.5 px-4 py-3 border-b border-border/40 bg-muted/30">
        <div className="flex items-center justify-center w-7 h-7 rounded-lg bg-primary/10 shrink-0">
          <KeyRound className="w-3.5 h-3.5 text-primary" />
        </div>
        <span className="font-medium text-sm text-foreground">{group.title}</span>
      </div>

      {/* Fields */}
      <div className="px-4 py-3 space-y-3">
        {group.fields.map((field) => (
          <div key={field.name} className="space-y-1">
            <label className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <span>{field.label}</span>
              <code className="text-[10px] px-1 py-0.5 rounded bg-muted text-muted-foreground/70">{field.name}</code>
            </label>
            <input
              type="text"
              placeholder={field.placeholder}
              value={values[field.name] || ''}
              onChange={(e) => handleChange(field.name, e.target.value)}
              disabled={status === 'submitting'}
              className="w-full px-3 py-2 rounded-lg text-sm bg-background border border-border/60 text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary/50 disabled:opacity-50 transition-colors font-mono"
              spellCheck={false}
              autoComplete="off"
            />
          </div>
        ))}
      </div>

      {/* Error message */}
      {status === 'error' && (
        <div className="px-4 pb-2 flex items-center gap-1.5 text-xs text-red-400">
          <AlertCircle className="w-3 h-3 shrink-0" />
          <span>{errorMsg}</span>
        </div>
      )}

      {/* Footer */}
      <div className="px-4 py-3 border-t border-border/40 bg-muted/20 flex items-center justify-between">
        <span className="text-[11px] text-muted-foreground/60">
          Values are written to <code className="text-[10px]">.env</code>
        </span>
        <button
          onClick={handleSubmit}
          disabled={filledCount === 0 || status === 'submitting'}
          className="inline-flex items-center gap-1.5 px-4 py-1.5 rounded-lg text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-40 disabled:cursor-not-allowed transition-all"
        >
          {status === 'submitting' ? (
            <>
              <Loader2 className="w-3 h-3 animate-spin" />
              Saving...
            </>
          ) : (
            'Submit'
          )}
        </button>
      </div>
    </div>
  );
}
