"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { SetupHeader, FieldLabel, TextInput, PrimaryButton, type SetupProps } from "./setup-shared";

export function ChatImportSetup({ workspace, onClose, onBack }: SetupProps) {
  const router = useRouter();
  const [name, setName] = useState("");
  const [chatText, setChatText] = useState("");
  const [loading, setLoading] = useState(false);

  const canCreate = name.trim().length > 0 && chatText.trim().length > 20;

  const handleCreate = async () => {
    if (!canCreate) return;
    setLoading(true);
    try {
      const res = await fetch("/api/projects/create", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          projectName: name.trim(),
          projectType: "web-app",
          slug: name.toLowerCase().replace(/[^a-z0-9]+/g, "-"),
          product: { name: name.trim() },
          creationMode: "chat-import",
          sourceData: { chatText: chatText.trim() },
        }),
      });
      if (!res.ok) {
        const err = await res.json();
        toast.error(err.error || "Failed to create project");
        return;
      }
      const data = await res.json();
      onClose();
      router.push(`/${workspace}/project/${data.projectId}/overview`);
    } catch {
      toast.error("Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ padding: "32px 36px 36px" }}>
      <SetupHeader
        icon="⌁" label="Import Chats" tagline="You've been thinking"
        accent="#2e5a4a" onBack={onBack} onClose={onClose}
      />

      <FieldLabel>Project name</FieldLabel>
      <TextInput
        value={name}
        onChange={setName}
        placeholder="What are you building?"
        autoFocus
      />

      <FieldLabel>Paste your chat history</FieldLabel>
      <textarea
        value={chatText}
        onChange={e => setChatText(e.target.value)}
        placeholder={"Paste conversations from ChatGPT, Claude, Gemini, or any AI tool.\n\nAtlas will extract decisions, ideas, open questions, and architecture notes."}
        rows={8}
        style={{
          width: "100%", padding: "12px 14px", marginBottom: 20,
          borderRadius: 8, border: "1px solid #e0dcd4",
          background: "#faf8f5", fontSize: "0.85rem", lineHeight: 1.55,
          fontFamily: "Outfit, sans-serif", color: "#1a1a1a",
          outline: "none", resize: "vertical", boxSizing: "border-box",
        }}
        onFocus={e => (e.currentTarget.style.borderColor = "#1a1a1a")}
        onBlur={e => (e.currentTarget.style.borderColor = "#e0dcd4")}
      />

      <PrimaryButton onClick={handleCreate} disabled={!canCreate} loading={loading}>
        Extract & analyse →
      </PrimaryButton>
    </div>
  );
}
