import { useState } from 'react'
import { useAIFlowBuilderStore } from '@/store/aiFlowBuilderStore'
import { QuotaDisplay } from './QuotaDisplay'
import { cn } from '@/lib/utils'

export function FoundationForm() {
  const { metadata, setMetadata, quota, start, isLoading, error } = useAIFlowBuilderStore()
  const [tagInput, setTagInput] = useState('')

  const canSubmit =
    metadata.name.trim().length > 0 &&
    metadata.description.trim().length > 0 &&
    !isLoading &&
    (quota?.allowed !== false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!canSubmit) return
    await start()
  }

  const addTag = () => {
    const tag = tagInput.trim()
    if (tag && !metadata.environment_tags.includes(tag)) {
      setMetadata({ environment_tags: [...metadata.environment_tags, tag] })
    }
    setTagInput('')
  }

  const removeTag = (tag: string) => {
    setMetadata({ environment_tags: metadata.environment_tags.filter((t) => t !== tag) })
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      {quota && <QuotaDisplay quota={quota} />}

      {/* Flow Type */}
      <div>
        <label className="mb-2 block font-label text-[0.6875rem] uppercase tracking-wide text-muted-foreground">
          Flow Type
        </label>
        <div className="flex gap-2">
          {(['troubleshooting', 'procedural'] as const).map((type) => (
            <button
              key={type}
              type="button"
              onClick={() => setMetadata({ flow_type: type })}
              className={cn(
                'flex-1 rounded-lg border px-3 py-2.5 text-sm font-medium transition-colors',
                metadata.flow_type === type
                  ? 'border-primary/30 bg-primary/10 text-foreground'
                  : 'border-border bg-card text-muted-foreground hover:bg-accent'
              )}
            >
              {type === 'troubleshooting' ? 'Troubleshooting' : 'Procedural'}
            </button>
          ))}
        </div>
      </div>

      {/* Name */}
      <div>
        <label className="mb-2 block font-label text-[0.6875rem] uppercase tracking-wide text-muted-foreground">
          Flow Name
        </label>
        <input
          type="text"
          value={metadata.name}
          onChange={(e) => setMetadata({ name: e.target.value })}
          placeholder="e.g. DNS Resolution Failures"
          className="w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
          maxLength={255}
        />
      </div>

      {/* Description */}
      <div>
        <label className="mb-2 block font-label text-[0.6875rem] uppercase tracking-wide text-muted-foreground">
          Description
        </label>
        <textarea
          value={metadata.description}
          onChange={(e) => setMetadata({ description: e.target.value })}
          placeholder="Describe what this flow covers. The more detail you provide, the better the AI suggestions will be."
          rows={4}
          className="w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20 resize-none"
          maxLength={2000}
        />
        <p className="mt-1 text-right text-[10px] text-muted-foreground">
          {metadata.description.length}/2000
        </p>
      </div>

      {/* Environment Tags */}
      <div>
        <label className="mb-2 block font-label text-[0.6875rem] uppercase tracking-wide text-muted-foreground">
          Environment Tags <span className="normal-case tracking-normal text-muted-foreground/60">(optional)</span>
        </label>
        <div className="flex gap-2">
          <input
            type="text"
            value={tagInput}
            onChange={(e) => setTagInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                e.preventDefault()
                addTag()
              }
            }}
            placeholder="e.g. Windows Server, Active Directory"
            className="flex-1 rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
          />
          <button
            type="button"
            onClick={addTag}
            className="rounded-lg border border-border px-3 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-foreground"
          >
            Add
          </button>
        </div>
        {metadata.environment_tags.length > 0 && (
          <div className="mt-2 flex flex-wrap gap-1.5">
            {metadata.environment_tags.map((tag) => (
              <span
                key={tag}
                className="inline-flex items-center gap-1 rounded-full bg-card border border-border px-2.5 py-0.5 font-label text-xs text-muted-foreground"
              >
                {tag}
                <button
                  type="button"
                  onClick={() => removeTag(tag)}
                  className="ml-0.5 text-muted-foreground/60 hover:text-foreground"
                >
                  &times;
                </button>
              </span>
            ))}
          </div>
        )}
      </div>

      {/* Error */}
      {error && (
        <div className="rounded-lg border border-red-400/20 bg-red-400/5 px-3 py-2 text-sm text-red-400">
          {error}
        </div>
      )}

      {/* Submit */}
      <button
        type="submit"
        disabled={!canSubmit}
        className={cn(
          'w-full rounded-lg bg-gradient-brand py-2.5 text-sm font-medium text-white shadow-lg shadow-primary/20',
          canSubmit ? 'hover:opacity-90' : 'cursor-not-allowed opacity-50'
        )}
      >
        {isLoading ? 'Creating...' : 'Continue to AI Scaffold'}
      </button>
    </form>
  )
}
