"use client";

import { useState } from "react";
import { trpc } from "~/lib/trpc/client.js";
import { usePermissions } from "~/hooks/usePermissions.js";
import { formatDate } from "~/lib/format.js";

interface Props {
  resourceId: string;
  aiSummary: string | null;
  aiSummaryUpdatedAt: Date | string | null;
  onGenerated: () => void;
}

export function AiSummaryCard({ resourceId, aiSummary, aiSummaryUpdatedAt, onGenerated }: Props) {
  const [localSummary, setLocalSummary] = useState<string | null>(aiSummary);
  const [localUpdatedAt, setLocalUpdatedAt] = useState<Date | string | null>(aiSummaryUpdatedAt);
  const [error, setError] = useState<string | null>(null);
  const { canEdit } = usePermissions();

  // Keep local state in sync if the parent refreshes with newer data
  if (aiSummary && aiSummary !== localSummary) {
    setLocalSummary(aiSummary);
    setLocalUpdatedAt(aiSummaryUpdatedAt);
  }

  const generateMutation = trpc.resource.generateAiSummary.useMutation({
    onSuccess: (data) => {
      setError(null);
      setLocalSummary(data.summary);
      setLocalUpdatedAt(new Date());
      onGenerated();
    },
    onError: (err) => {
      setError(err.message ?? "Failed to generate summary");
    },
  });

  const { data: aiConfigured } = trpc.settings.getAiConfigured.useQuery(undefined, {
    staleTime: 5_000,
  });

  return (
    <div className="bg-white rounded-xl border border-gray-200 p-5">
      <div className="flex items-center justify-between mb-3">
        <h2 className="text-sm font-semibold text-gray-800">AI Profile Summary</h2>
        {canEdit && aiConfigured?.configured && (
          <button
            type="button"
            onClick={() => generateMutation.mutate({ resourceId })}
            disabled={generateMutation.isPending}
            className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg bg-brand-50 text-brand-700 hover:bg-brand-100 disabled:opacity-50 transition-colors"
          >
            {generateMutation.isPending ? (
              <>
                <svg className="animate-spin h-3 w-3" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                </svg>
                Generating…
              </>
            ) : localSummary ? (
              "Regenerate"
            ) : (
              "Generate"
            )}
          </button>
        )}
      </div>

      {error && (
        <div className="mb-3 rounded-lg bg-red-50 border border-red-200 px-3 py-2 text-xs text-red-700">
          {error}
        </div>
      )}

      {localSummary ? (
        <>
          <span className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] font-medium rounded bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300 mb-2">
            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
            </svg>
            AI Generated
          </span>
          <p className="text-sm text-gray-700 leading-relaxed">{localSummary}</p>
          {localUpdatedAt && (
            <p className="text-xs text-gray-400 mt-2">
              Generated {formatDate(localUpdatedAt)}
            </p>
          )}
        </>
      ) : (
        <p className="text-sm text-gray-400 italic">
          {!aiConfigured?.configured
            ? "AI not configured. Set up your API key in Admin → Settings."
            : canEdit
            ? "No summary yet. Click Generate to create one."
            : "No summary generated yet."}
        </p>
      )}
    </div>
  );
}
