import { FolderGit2, Globe, Lock, X } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';

import { useCreateWorkspace } from '@/hooks/workspace/useCreateWorkspace';

import { VisibilityOption } from './ui/VisibilityOption';

interface CreateWorkspaceModalProps {
  open: boolean;
  onClose: () => void;
}

export function CreateWorkspaceModal({ open, onClose }: CreateWorkspaceModalProps) {
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [visibility, setVisibility] = useState('private');
  const [error, setError] = useState<string | null>(null);

  const createMutation = useCreateWorkspace();
  const inputRef = useRef<HTMLInputElement>(null);
  const resetMutationRef = useRef(createMutation.reset);
  resetMutationRef.current = createMutation.reset;

  // Focus input on open, reset form on close
  useEffect(() => {
    if (open) {
      setName('');
      setDescription('');
      setVisibility('private');
      setError(null);
      resetMutationRef.current();
      setTimeout(() => inputRef.current?.focus(), 50);
    }
  }, [open]);

  // Escape to close
  useEffect(() => {
    if (!open) return;
    function handleKey(e: KeyboardEvent) {
      if (e.key === 'Escape') onClose();
    }
    document.addEventListener('keydown', handleKey);
    return () => document.removeEventListener('keydown', handleKey);
  }, [open, onClose]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (!name.trim()) {
      setError('Workspace name is required.');
      return;
    }
    try {
      await createMutation.mutateAsync({
        name: name.trim(),
        description: description.trim() || undefined,
        visibility: visibility || undefined,
      });
      onClose();
    } catch (err) {
      setError((err as Error)?.message ?? 'Failed to create workspace.');
    }
  }

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center">
      <button
        type="button"
        aria-label="Close"
        className="absolute inset-0 bg-background/50 backdrop-blur-[2px] border-0 p-0 cursor-default"
        onClick={onClose}
      />

      <div className="relative w-full max-w-[440px] rounded-xl bg-card shadow-[0_12px_32px_rgba(0,0,0,0.12)] ring-1 ring-border">
        {/* Header */}
        <div className="flex items-center justify-between px-5 pt-5 pb-3">
          <div className="flex items-center gap-3">
            <div className="flex size-9 items-center justify-center rounded-lg bg-muted">
              <FolderGit2 className="size-5 text-muted-foreground" />
            </div>
            <h2 className="text-[16px] font-semibold text-foreground">Create workspace</h2>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
          >
            <X className="size-4" />
          </button>
        </div>

        <form onSubmit={handleSubmit}>
          {/* Body */}
          <div className="px-5 py-2 space-y-4">
            {/* Name */}
            <div>
              <label
                htmlFor="ws-name"
                className="mb-1.5 block text-[13px] font-semibold text-foreground"
              >
                Workspace name <span className="text-destructive">*</span>
              </label>
              <input
                ref={inputRef}
                id="ws-name"
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="my-awesome-team"
                className="w-full rounded-md border border-border bg-card px-3 py-[7px] text-[14px] leading-[20px] text-foreground outline-none transition-shadow placeholder:text-muted-foreground/50 focus:shadow-[inset_0_0_0_2px_var(--ring)] focus:border-transparent"
              />
              <p className="mt-1 text-[12px] text-muted-foreground">
                Must be unique. Use lowercase letters, numbers, and hyphens.
              </p>
            </div>

            {/* Description */}
            <div>
              <label
                htmlFor="ws-desc"
                className="mb-1.5 block text-[13px] font-semibold text-foreground"
              >
                Description
              </label>
              <textarea
                id="ws-desc"
                rows={3}
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="What's this workspace for?"
                className="w-full rounded-md border border-border bg-card px-3 py-[7px] text-[14px] leading-[20px] text-foreground outline-none transition-shadow placeholder:text-muted-foreground/50 focus:shadow-[inset_0_0_0_2px_var(--ring)] focus:border-transparent resize-none"
              />
            </div>

            {/* Visibility */}
            <div>
              <span className="mb-2 block text-[13px] font-semibold text-foreground">
                Visibility
              </span>
              <div className="space-y-2">
                <VisibilityOption
                  value="private"
                  label="Private"
                  description="Only invited members can see and access this workspace."
                  icon={Lock}
                  selected={visibility === 'private'}
                  onChange={setVisibility}
                />
                <VisibilityOption
                  value="internal"
                  label="Internal"
                  description="All organization members can see this workspace."
                  icon={Globe}
                  selected={visibility === 'internal'}
                  onChange={setVisibility}
                />
                <VisibilityOption
                  value="public"
                  label="Public"
                  description="Anyone on the internet can see this workspace."
                  icon={Globe}
                  selected={visibility === 'public'}
                  onChange={setVisibility}
                />
              </div>
            </div>

            {/* Error */}
            {error && (
              <div className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-[13px] text-destructive">
                {error}
              </div>
            )}
          </div>

          {/* Footer */}
          <div className="flex items-center justify-end gap-2 border-t border-border px-5 py-4 mt-2">
            <button
              type="button"
              onClick={onClose}
              className="rounded-md px-4 py-[6px] text-[13px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={createMutation.isPending || !name.trim()}
              className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-[6px] text-[13px] font-medium text-primary-foreground transition-colors hover:bg-primary/85 disabled:opacity-50"
            >
              {createMutation.isPending && (
                <span className="inline-block size-3.5 animate-spin rounded-full border-2 border-primary-foreground/40 border-t-primary-foreground" />
              )}
              {createMutation.isPending ? 'Creating…' : 'Create workspace'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
