"use client";

import React, { useState, useEffect } from "react";
import { useDocumentInfo } from "@payloadcms/ui";
import { toast } from "@payloadcms/ui";

export const AiAnalyzeButton: React.FC = () => {
  const { id } = useDocumentInfo();
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [hasWebsite, setHasWebsite] = useState(false);

  useEffect(() => {
    // Basic check if a website URL is likely present - would ideally check true document state
    // but the fields might not be fully available in this context depending on Payload version.
    // For now we just enable the button and the backend will validate.
    setHasWebsite(true);
  }, []);

  const handleAnalyze = async (e: React.MouseEvent) => {
    e.preventDefault();
    if (!id) return;

    setIsAnalyzing(true);
    toast.info(
      "Starting AI analysis for this account. This may take a few minutes...",
    );

    try {
      const response = await fetch(`/api/crm-accounts/${id}/analyze`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || "Analysis failed");
      }

      toast.success(
        result.message ||
          "Analysis started in background. The page will update when finished.",
      );
      // Removed router.refresh() here because the background task takes ~60s
    } catch (error) {
      console.error("Analysis error:", error);
      toast.error(
        error instanceof Error
          ? error.message
          : "An error occurred during analysis",
      );
    } finally {
      setIsAnalyzing(false);
    }
  };

  if (!id) return null; // Only show on existing documents, not when creating new

  return (
    <div style={{ marginBottom: "2rem", marginTop: "1rem" }}>
      <button
        onClick={handleAnalyze}
        disabled={isAnalyzing || !hasWebsite}
        className="btn btn--style-primary btn--icon-style-none btn--size-medium"
        type="button"
        style={{
          background: "var(--theme-elevation-150)",
          border: "1px solid var(--theme-elevation-200)",
          color: "var(--theme-text)",
          padding: "8px 16px",
          borderRadius: "4px",
          fontSize: "14px",
          cursor: isAnalyzing || !hasWebsite ? "not-allowed" : "pointer",
          display: "inline-flex",
          alignItems: "center",
          gap: "8px",
          opacity: isAnalyzing || !hasWebsite ? 0.6 : 1,
          fontWeight: "500",
        }}
      >
        {isAnalyzing ? "✨ AI analysiert..." : "✨ AI Website Analyse starten"}
      </button>
      <p
        style={{
          fontSize: "0.85rem",
          color: "var(--theme-elevation-600)",
          marginTop: "0.75rem",
          maxWidth: "400px",
          lineHeight: "1.4",
        }}
      >
        <strong>Note:</strong> This will crawl the website, generate a strategy
        concept, and create a budget estimation. The resulting PDFs will be
        attached to the "AI Reports" field below.
      </p>
    </div>
  );
};
