/**
 * GenerateBriefModal — shared "Generate Content Brief" dialog used by
 * Freshness/Show and TopicClusters/Show (and any future content-intel detail page).
 *
 * Cost/model copy is derived from the `modelLabel` prop, which the parent resolves
 * from the `ai_defaults` shared prop. Keeping usePage() out of this component makes
 * it testable without an Inertia context wrapper.
 *
 * NEW-CI-007: when `serpKeyAvailable` is false, renders an honest scope-downgrade
 * notice BEFORE dispatch so the user knows the brief will be generated from GSC data
 * only (no competitor terms, word-count benchmarks, or coverage gaps).
 */
import { type FormEvent } from 'react';

import { Link } from '@inertiajs/react';

import { Button } from '@/Components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/Components/ui/dialog';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import { Textarea } from '@/Components/ui/textarea';

interface GenerateBriefModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** Pre-filled keyword (cluster name, recommendation title, etc.) */
  targetKeyword: string;
  onTargetKeywordChange: (value: string) => void;
  /** Optional custom instructions value */
  customInstructions: string;
  onCustomInstructionsChange: (value: string) => void;
  onSubmit: (e: FormEvent) => void;
  processing: boolean;
  errors: Partial<{ target_keyword: string; custom_instructions: string }>;
  /** Description shown in DialogDescription — customise per use-case */
  description?: string;
  /**
   * Human-readable model label resolved from `ai_defaults.allowed_models[0]`
   * by the parent (keeps usePage() out of this component for testability).
   * Defaults to "your configured AI provider" if omitted.
   */
  modelLabel?: string;
  /**
   * NEW-CI-007: true when the user has a validated DataForSEO key.
   * When false, renders a scope-downgrade notice before dispatch.
   * Defaults to true so call-sites that haven't been updated yet are unaffected.
   */
  serpKeyAvailable?: boolean;
  /**
   * Optional placeholder for the custom instructions textarea.
   * Defaults to the generic hint; hosts can supply a use-case-specific one
   * (e.g., the Cannibalization host sets a consolidation-specific hint).
   */
  customInstructionsPlaceholder?: string;
}

export default function GenerateBriefModal({
  open,
  onOpenChange,
  targetKeyword,
  onTargetKeywordChange,
  customInstructions,
  onCustomInstructionsChange,
  onSubmit,
  processing,
  errors,
  description = 'Create a comprehensive content brief using your configured AI provider.',
  modelLabel = 'your configured AI provider',
  serpKeyAvailable = true,
  customInstructionsPlaceholder = 'Add any specific instructions (e.g., tone, audience, focus areas)',
}: GenerateBriefModalProps) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Generate Content Brief</DialogTitle>
          <DialogDescription>{description}</DialogDescription>
        </DialogHeader>
        <form onSubmit={onSubmit} className="space-y-4">
          <div>
            <Label htmlFor="brief-target-keyword">Target Keyword</Label>
            <Input
              id="brief-target-keyword"
              type="text"
              value={targetKeyword}
              onChange={(e) => onTargetKeywordChange(e.target.value)}
              placeholder="Enter target keyword or topic"
              required
              className="mt-1"
            />
            {errors.target_keyword && (
              <p className="text-sm text-destructive mt-1">{errors.target_keyword}</p>
            )}
          </div>

          <div>
            <Label htmlFor="brief-custom-instructions">Custom Instructions (Optional)</Label>
            <Textarea
              id="brief-custom-instructions"
              value={customInstructions}
              onChange={(e) => onCustomInstructionsChange(e.target.value)}
              placeholder={customInstructionsPlaceholder}
              rows={4}
              className="mt-1"
            />
            {errors.custom_instructions && (
              <p className="text-sm text-destructive mt-1">{errors.custom_instructions}</p>
            )}
          </div>

          {/* NEW-CI-007: scope preview — conditional on serpKeyAvailable */}
          {serpKeyAvailable ? (
            <div className="rounded-lg border bg-muted/50 p-3">
              <p className="text-sm font-medium mb-2">Brief will include:</p>
              <ul className="text-xs text-muted-foreground space-y-1 list-disc list-inside">
                <li>Recommended H1 and H2 structure</li>
                <li>Key entities and topics to cover</li>
                <li>Target word count range</li>
                <li>Internal linking suggestions</li>
                <li>Audience context and competitive positioning</li>
              </ul>
            </div>
          ) : (
            <div className="rounded-lg border border-warning-border bg-warning-soft p-3">
              <p className="text-sm font-medium text-warning-strong mb-1">Generic brief (no competitor data)</p>
              <p className="text-xs text-muted-foreground">
                Without a DataForSEO key this brief is generated from your GSC data only — no competitor
                terms, word-count benchmarks, or coverage gaps.{' '}
                <Link
                  href={route('settings.serp')}
                  className="underline text-foreground hover:text-primary"
                >
                  Add a DataForSEO key
                </Link>{' '}
                to unlock SERP-grounded briefs.
              </p>
            </div>
          )}

          <div className="rounded-lg border bg-muted/50 p-3">
            <p className="text-sm font-medium mb-1">AI usage:</p>
            <p className="text-xs text-muted-foreground">
              Uses ~1,300 tokens of <span className="font-medium">{modelLabel}</span>. Charged to your
              configured API key.
            </p>
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={processing}
            >
              Cancel
            </Button>
            <LoadingButton loading={processing} loadingText="Generating...">
              Generate Brief
            </LoadingButton>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
