import { useState, useEffect } from 'react'
import { GitBranch, X } from 'lucide-react'
import { treesApi } from '@/api/trees'
import { toast } from '@/lib/toast'
import { cn } from '@/lib/utils'
import { useNavigate } from 'react-router-dom'
import { Button } from '@/components/ui/Button'

interface ForkModalProps {
  treeId: string
  treeName: string
  onClose: () => void
}

export function ForkModal({ treeId, treeName, onClose }: ForkModalProps) {
  const navigate = useNavigate()
  const [name, setName] = useState(`Copy of ${treeName}`)
  const [forkReason, setForkReason] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [onClose])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!name.trim()) return
    setIsSubmitting(true)
    setError(null)
    try {
      await treesApi.fork(treeId, {
        name: name.trim(),
        fork_reason: forkReason.trim() || undefined,
      })
      toast.success('Flow forked successfully')
      onClose()
      navigate('/my-trees')
    } catch (err) {
      console.error('Failed to fork flow:', err)
      setError('Failed to fork flow. Please try again.')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
      onClick={onClose}
    >
      <div
        className="w-full max-w-md rounded-xl border border-border bg-card shadow-xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between border-b border-border px-5 py-4">
          <div className="flex items-center gap-2">
            <GitBranch className="h-4 w-4 text-muted-foreground" />
            <h2 className="text-sm font-semibold text-foreground">Fork Flow</h2>
          </div>
          <button
            onClick={onClose}
            aria-label="Close"
            className="rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* Body */}
        <form onSubmit={handleSubmit} className="space-y-4 px-5 py-4">
          <div>
            <label htmlFor="fork-name" className="mb-1.5 block text-xs font-medium text-muted-foreground">
              Name <span className="text-red-400">*</span>
            </label>
            <input
              id="fork-name"
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              required
              autoFocus
              maxLength={255}
              className={cn(
                '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-hidden focus:ring-1 focus:ring-primary/20'
              )}
            />
          </div>

          <div>
            <label htmlFor="fork-reason" className="mb-1.5 block text-xs font-medium text-muted-foreground">
              Reason for Forking{' '}
              <span className="text-muted-foreground/60">(optional)</span>
            </label>
            <textarea
              id="fork-reason"
              value={forkReason}
              onChange={(e) => setForkReason(e.target.value)}
              rows={3}
              placeholder="e.g. customizing for a specific client…"
              className={cn(
                'w-full resize-none rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground',
                'placeholder:text-muted-foreground focus:border-primary focus:outline-hidden focus:ring-1 focus:ring-primary/20'
              )}
            />
          </div>

          {error && (
            <p className="text-xs text-red-400">{error}</p>
          )}

          {/* Footer */}
          <div className="flex justify-end gap-2 pt-1">
            <Button
              type="button"
              variant="secondary"
              onClick={onClose}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={!name.trim()}
              loading={isSubmitting}
            >
              Fork Flow
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
}
