"use client";

import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Globe, Loader2 } from "lucide-react";
import { api, ApiError } from "@/lib/api";
import { isValidUrl } from "@/lib/constants";
import { useSiteInspectionStore } from "@/stores/useSiteInspectionStore";
import { cn } from "@/lib/utils";
import {
  AccessibilityStandardSelect,
  type AccessibilityStandard,
} from "./AccessibilityStandardSelect";

/** 최대 페이지 수 옵션 (0 = 무제한) */
const MAX_PAGES_OPTIONS = [10, 20, 50, 0] as const;

/** 크롤링 깊이 옵션 */
const MAX_DEPTH_OPTIONS = [1, 2, 3] as const;

/** 동시 검사 수 옵션 */
const CONCURRENCY_OPTIONS = [1, 2, 4, 8] as const;

/** 사이트 크롤링 폼 */
export function SiteCrawlForm() {
  const [url, setUrl] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [maxPages, setMaxPages] = useState<number>(20);
  const [maxDepth, setMaxDepth] = useState<number>(2);
  const [concurrency, setConcurrency] = useState<number>(4);
  const [accessibilityStandard, setAccessibilityStandard] =
    useState<AccessibilityStandard>("wcag_2.1_aa");
  const router = useRouter();
  const { setSiteInspection } = useSiteInspectionStore();

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError(null);

    const trimmedUrl = url.trim();
    if (!trimmedUrl) {
      setError("URL을 입력해주세요");
      return;
    }
    if (!isValidUrl(trimmedUrl)) {
      setError("유효한 URL을 입력해주세요 (http:// 또는 https://로 시작)");
      return;
    }

    setIsLoading(true);

    try {
      const response = await api.startSiteInspection(
        trimmedUrl,
        maxPages,
        maxDepth,
        concurrency,
        accessibilityStandard
      );
      setSiteInspection(response.site_inspection_id, trimmedUrl);
      router.push(
        `/site-inspections/${response.site_inspection_id}/progress`
      );
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.detail);
      } else {
        setError("사이트 크롤링 시작 중 오류가 발생했습니다. 다시 시도해주세요.");
      }
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Card className="w-full max-w-2xl mx-auto">
      <CardContent className="pt-6">
        <form onSubmit={handleSubmit} className="flex flex-col gap-4">
          {/* URL 입력 필드 */}
          <div className="relative">
            <Globe className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              type="text"
              value={url}
              onChange={(e) => {
                setUrl(e.target.value);
                if (error) setError(null);
              }}
              placeholder="https://example.com"
              className="pl-10 h-12 text-base"
              disabled={isLoading}
              aria-label="크롤링할 사이트 URL 입력"
              aria-invalid={!!error}
              aria-describedby={error ? "site-url-error" : undefined}
            />
          </div>

          {/* 옵션 영역 */}
          <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
            {/* 최대 페이지 수 */}
            <div>
              <label className="text-xs text-muted-foreground mb-1.5 block">
                최대 페이지 수
              </label>
              <div className="flex gap-1.5">
                {MAX_PAGES_OPTIONS.map((option) => (
                  <Button
                    key={option}
                    type="button"
                    variant={maxPages === option ? "default" : "outline"}
                    size="sm"
                    className={cn(
                      "flex-1 text-xs",
                      maxPages === option && "pointer-events-none"
                    )}
                    onClick={() => setMaxPages(option)}
                    disabled={isLoading}
                  >
                    {option === 0 ? "무제한" : option}
                  </Button>
                ))}
              </div>
            </div>

            {/* 크롤링 깊이 */}
            <div>
              <label className="text-xs text-muted-foreground mb-1.5 block">
                크롤링 깊이
              </label>
              <div className="flex gap-1.5">
                {MAX_DEPTH_OPTIONS.map((option) => (
                  <Button
                    key={option}
                    type="button"
                    variant={maxDepth === option ? "default" : "outline"}
                    size="sm"
                    className={cn(
                      "flex-1 text-xs",
                      maxDepth === option && "pointer-events-none"
                    )}
                    onClick={() => setMaxDepth(option)}
                    disabled={isLoading}
                  >
                    {option}
                  </Button>
                ))}
              </div>
            </div>

            {/* 동시 검사 수 */}
            <div>
              <label className="text-xs text-muted-foreground mb-1.5 block">
                동시 검사 수
              </label>
              <div className="flex gap-1.5">
                {CONCURRENCY_OPTIONS.map((option) => (
                  <Button
                    key={option}
                    type="button"
                    variant={concurrency === option ? "default" : "outline"}
                    size="sm"
                    className={cn(
                      "flex-1 text-xs",
                      concurrency === option && "pointer-events-none"
                    )}
                    onClick={() => setConcurrency(option)}
                    disabled={isLoading}
                  >
                    {option}
                  </Button>
                ))}
              </div>
            </div>

            {/* 접근성 기준 */}
            <AccessibilityStandardSelect
              value={accessibilityStandard}
              onChange={setAccessibilityStandard}
              disabled={isLoading}
            />
          </div>

          {/* 사이트 크롤링 시작 버튼 */}
          <Button
            type="submit"
            size="lg"
            className="h-12 text-base w-full"
            disabled={isLoading}
          >
            {isLoading ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                크롤링 시작 중...
              </>
            ) : (
              <>
                <Globe className="h-4 w-4" />
                사이트 크롤링 시작
              </>
            )}
          </Button>
        </form>

        {error && (
          <p
            id="site-url-error"
            className="mt-2 text-sm text-destructive"
            role="alert"
          >
            {error}
          </p>
        )}
      </CardContent>
    </Card>
  );
}
