import React, { useEffect, useMemo, useState } from 'react';

import { recomaze_ai_personalization_env } from '../env';
import {
  fetchLlmHits,
  fetchLlmStatus,
  generateLlmNow,
} from '../service/llm/llm.service';
import type {
  ILlmHitsResponse,
  ILlmStatus,
} from '../service/llm/llm.interface';
import LineChart from '../components/charts/LineChart';

const LlmTxtPage = (): JSX.Element => {
  const [status, setStatus] = useState<ILlmStatus | null>(null);
  const [hits, setHits] = useState<ILlmHitsResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [loadingHits, setLoadingHits] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [hitsError, setHitsError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  const loadStatus = async () => {
    setError(null);
    setLoading(true);
    try {
      const data = await fetchLlmStatus();
      setStatus(data);
    } catch (err: any) {
      setError(err?.message || 'Unable to load llm.txt status.');
    } finally {
      setLoading(false);
    }
  };

  const loadHits = async () => {
    setHitsError(null);
    setLoadingHits(true);
    try {
      const data = await fetchLlmHits(7);
      setHits(data);
    } catch (err: any) {
      setHitsError(err?.message || 'Unable to load llm.txt hits.');
    } finally {
      setLoadingHits(false);
    }
  };

  useEffect(() => {
    loadStatus();
    loadHits();
  }, []);

  const handleGenerate = async () => {
    setError(null);
    setSuccessMessage(null);
    setLoading(true);
    try {
      const data = await generateLlmNow();
      setStatus(data);
      await loadHits();
      const products = data?.counts?.products ?? 0;
      const pages = data?.counts?.pages ?? 0;
      setSuccessMessage(
        `Successfully generated llm.txt with ${products} products and ${pages} pages.`
      );
      setTimeout(() => setSuccessMessage(null), 5000);
    } catch (err: any) {
      setError(err?.message || 'Generation failed.');
    } finally {
      setLoading(false);
    }
  };

  const llmUrl =
    status?.llm_url ||
    recomaze_ai_personalization_env?.llm_url ||
    recomaze_ai_personalization_env?.wp_api_url?.replace(/\/$/, '') +
      '/llm.txt';

  const chartData = useMemo(
    () => ({
      labels: hits?.hits_by_day?.map(d => d.label) || [],
      datasets: [
        {
          label: 'Requests',
          data: hits?.hits_by_day?.map(d => d.count) || [],
          fill: true,
          tension: 0.35,
          borderColor: '#111827',
          backgroundColor: 'rgba(17, 24, 39, 0.05)',
        },
      ],
    }),
    [hits?.hits_by_day]
  );

  const totalHits = useMemo(
    () => hits?.hits_by_day?.reduce((sum, d) => sum + (d?.count || 0), 0) || 0,
    [hits?.hits_by_day]
  );

  return (
    <div className="mx-auto w-full max-w-[1600px] space-y-6 bg-white p-6 md:p-10">
      <header className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-xl font-medium tracking-tight text-gray-900 md:text-2xl">
            LLM.txt Configuration
          </h1>
          <p className="mt-1 text-sm text-gray-500">
            Manage the feed used by GPT, Claude, and Perplexity bots to index
            your catalog.
          </p>
        </div>
        <div className="flex shrink-0 items-center gap-3">
          <a
            href={llmUrl}
            target="_blank"
            rel="noreferrer noopener"
            className="inline-flex h-10 items-center justify-center rounded-md border border-gray-200 bg-white px-4 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50"
          >
            Open llm.txt
          </a>
          <button
            onClick={handleGenerate}
            disabled={loading}
            className="inline-flex h-10 w-[140px] items-center justify-center rounded-md bg-gray-900 px-4 text-sm font-medium text-white transition-colors hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-50"
          >
            {loading ? (
              <svg
                className="mr-2 h-4 w-4 animate-spin"
                viewBox="0 0 24 24"
                fill="none"
              >
                <circle
                  cx="12"
                  cy="12"
                  r="10"
                  stroke="currentColor"
                  strokeWidth="3"
                  className="opacity-20"
                />
                <path
                  fill="currentColor"
                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                />
              </svg>
            ) : null}
            {loading ? 'Generating…' : 'Generate Now'}
          </button>
        </div>
      </header>

      {successMessage && (
        <div className="rounded-md bg-emerald-50 p-4 ring-1 ring-inset ring-emerald-600/20">
          <div className="flex items-start gap-3">
            <svg
              className="mt-0.5 h-4 w-4 shrink-0 text-emerald-600"
              fill="currentColor"
              viewBox="0 0 20 20"
            >
              <path
                fillRule="evenodd"
                d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                clipRule="evenodd"
              />
            </svg>
            <p className="text-sm font-medium text-emerald-900">
              {successMessage}
            </p>
          </div>
        </div>
      )}

      {error && (
        <div className="rounded-md bg-red-50 p-4 ring-1 ring-inset ring-red-600/20">
          <p className="text-sm font-medium text-red-900">{error}</p>
        </div>
      )}

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        <section className="flex flex-col overflow-hidden rounded-lg border border-gray-200 bg-white">
          <header className="border-b border-gray-100 bg-gray-50/50 px-5 py-4">
            <h2 className="text-sm font-medium text-gray-900">
              Current Status
            </h2>
          </header>
          <div className="flex-1 p-5">
            <div className="mb-6 flex items-center justify-between rounded-md border border-gray-100 bg-gray-50 px-4 py-3">
              <div className="flex flex-col">
                <span className="text-xs font-medium text-gray-500">
                  Last Generated
                </span>
                <span className="text-sm font-medium text-gray-900">
                  {status?.generated_at
                    ? new Date(status.generated_at).toLocaleString()
                    : 'Never'}
                </span>
              </div>
              {status?.cached && (
                <span className="inline-flex items-center rounded-md bg-white px-2 py-1 text-xs font-medium text-gray-600 ring-1 ring-inset ring-gray-200">
                  Cached
                </span>
              )}
            </div>

            <div className="grid grid-cols-3 gap-4 border-b border-gray-100 pb-6">
              <div>
                <p className="text-xs font-medium text-gray-500">Products</p>
                <p className="mt-1 text-2xl font-medium text-gray-900">
                  {status?.counts?.products ?? '—'}
                </p>
              </div>
              <div>
                <p className="text-xs font-medium text-gray-500">Pages</p>
                <p className="mt-1 text-2xl font-medium text-gray-900">
                  {status?.counts?.pages ?? '—'}
                </p>
              </div>
              <div>
                <p className="text-xs font-medium text-gray-500">Total URLs</p>
                <p className="mt-1 text-2xl font-medium text-gray-900">
                  {status?.counts?.total ?? '—'}
                </p>
              </div>
            </div>

            {status?.warnings && status.warnings.length > 0 && (
              <div className="mt-6 space-y-2">
                <h3 className="text-xs font-semibold text-gray-900 uppercase tracking-wider">
                  Warnings
                </h3>
                <ul className="space-y-1">
                  {status.warnings.map((w, idx) => (
                    <li
                      key={idx}
                      className="flex items-start gap-2 text-sm text-amber-700"
                    >
                      <span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500" />
                      {w}
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        </section>

        <section className="flex flex-col overflow-hidden rounded-lg border border-gray-200 bg-white">
          <header className="border-b border-gray-100 bg-gray-50/50 px-5 py-4">
            <h2 className="text-sm font-medium text-gray-900">About llm.txt</h2>
          </header>
          <div className="flex-1 p-5 text-sm text-gray-600">
            <p className="mb-4">
              llm.txt exposes a clean list of products and pages for LLM
              crawlers (e.g., GPTBot, ClaudeBot) in a simple text format. Data
              is generated from your catalog, sanitized from HTML, and cached
              for performance.
            </p>
            <div className="mb-6 rounded-md bg-gray-50 px-3 py-2 font-mono text-xs text-gray-800 ring-1 ring-inset ring-gray-200">
              TYPE | URL | TITLE | SUMMARY
            </div>

            <h3 className="mb-2 font-medium text-gray-900">Best Practices</h3>
            <ul className="space-y-2">
              <li className="flex items-start gap-2">
                <span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-gray-300" />
                <span>
                  Ensure GPTBot and ClaudeBot are not blocked in your{' '}
                  <code className="rounded bg-gray-100 px-1 py-0.5 font-mono text-xs">
                    robots.txt
                  </code>
                  .
                </span>
              </li>
              <li className="flex items-start gap-2">
                <span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-gray-300" />
                <span>
                  Keep the storefront publicly accessible (no passwords) so URLs
                  can be indexed.
                </span>
              </li>
              <li className="flex items-start gap-2">
                <span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-gray-300" />
                <span>
                  Regenerate this file when you make significant changes to your
                  catalog.
                </span>
              </li>
            </ul>
          </div>
        </section>
      </div>

      <section className="overflow-hidden rounded-lg border border-gray-200 bg-white">
        <header className="flex items-center justify-between border-b border-gray-100 bg-gray-50/50 px-5 py-4">
          <h2 className="text-sm font-medium text-gray-900">
            Traffic Analysis (Last 7 Days)
          </h2>
          {hitsError && (
            <span className="text-xs text-red-600">{hitsError}</span>
          )}
        </header>
        <div className="p-5">
          {loadingHits ? (
            <div className="flex h-[280px] w-full items-center justify-center rounded-md border border-dashed border-gray-200 bg-gray-50">
              <span className="text-sm text-gray-500">
                Loading traffic data...
              </span>
            </div>
          ) : hits?.hits_by_day?.length ? (
            <div className="h-[280px] w-full">
              <LineChart
                data={chartData}
                width={800}
                height={280}
                total={totalHits}
              />
            </div>
          ) : (
            <div className="flex h-[280px] w-full items-center justify-center rounded-md border border-dashed border-gray-200 bg-gray-50">
              <span className="text-sm text-gray-500">
                No hits recorded in the last 7 days.
              </span>
            </div>
          )}
        </div>
      </section>

      <section className="overflow-hidden rounded-lg border border-gray-200 bg-white">
        <header className="border-b border-gray-100 bg-gray-50/50 px-5 py-4">
          <h2 className="text-sm font-medium text-gray-900">
            Recent Crawler Activity
          </h2>
        </header>

        {hits?.recent && hits.recent.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm text-gray-600">
              <thead className="border-b border-gray-100 bg-gray-50/50 text-xs font-medium text-gray-500">
                <tr>
                  <th className="px-5 py-3 font-medium">Timestamp</th>
                  <th className="px-5 py-3 font-medium">Bot Name</th>
                  <th className="px-5 py-3 font-medium">User Agent</th>
                  <th className="px-5 py-3 font-medium">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 bg-white">
                {hits.recent.map(hit => (
                  <tr
                    key={hit.id}
                    className="transition-colors hover:bg-gray-50"
                  >
                    <td className="whitespace-nowrap px-5 py-3 text-gray-900">
                      {new Date(hit.created_at).toLocaleString()}
                    </td>
                    <td className="whitespace-nowrap px-5 py-3 font-medium text-gray-900">
                      {hit.bot_name}
                    </td>
                    <td className="px-5 py-3">
                      <span
                        className="line-clamp-1 max-w-xs break-all text-xs"
                        title={hit.user_agent}
                      >
                        {hit.user_agent}
                      </span>
                    </td>
                    <td className="whitespace-nowrap px-5 py-3">
                      <span
                        className={`inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset ${
                          hit.status === 200
                            ? 'bg-emerald-50 text-emerald-700 ring-emerald-600/20'
                            : 'bg-red-50 text-red-700 ring-red-600/20'
                        }`}
                      >
                        {hit.status}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="flex h-32 items-center justify-center">
            <span className="text-sm text-gray-500">
              No recent crawler activity found.
            </span>
          </div>
        )}
      </section>
    </div>
  );
};

export default LlmTxtPage;
