import { FileText } from 'lucide-react';

import { useEffect, useState } from 'react';

import { Head, Link, useForm } from '@inertiajs/react';

import DecayPatternBadge from '@/Components/ContentIntelligence/DecayPatternBadge';
import FreshnessScoreCard from '@/Components/ContentIntelligence/FreshnessScoreCard';
import SiteNav from '@/Components/Navigation/SiteNav';
import { Badge } from '@/Components/ui/badge';
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';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEvent } from '@/lib/analytics';
import { FRESHNESS_ANALYSIS_VIEWED } from '@/lib/event-catalog';
import { formatDateOnly, formatPercent } from '@/lib/format';
import type { FreshnessShowPageProps } from '@/types/freshness';

function actionLabel(type: string): string {
  switch (type) {
    case 'light_refresh':
      return 'Light Refresh';
    case 'section_refresh':
      return 'Section Refresh';
    case 'full_rewrite':
      return 'Full Rewrite';
    case 'reposition_intent':
      return 'Reposition Intent';
    default:
      return type;
  }
}

export default function FreshnessShow({
  site,
  recommendation,
  decaySignal,
  decayRun,
  wpPost,
}: FreshnessShowPageProps) {
  useEffect(() => {
    trackEvent(FRESHNESS_ANALYSIS_VIEWED, { site_id: String(site.id) });
  }, [site.id]);

  const [isGenerateBriefModalOpen, setIsGenerateBriefModalOpen] = useState(false);
  const { data, setData, post, processing, reset, errors } = useForm({
    target_keyword: recommendation.title || '',
    custom_instructions: '',
    source_type: 'FreshnessRecommendation',
    source_id: recommendation.id,
  });

  const handleGenerateBrief = (e: React.FormEvent) => {
    e.preventDefault();
    post(route('content-briefs.store', site.id), {
      onSuccess: () => {
        setIsGenerateBriefModalOpen(false);
        reset();
      },
    });
  };

  return (
    <>
      <Head title={`${site.name} - ${recommendation.title}`} />

      <div className="container py-6">
        <SiteNav
          siteId={site.id}
          canAnalyze
          canRecommend
          canCannibalization
          canOpportunityMap
          canGeographic
          canDevice
        />

        <div className="flex items-center justify-between gap-3 mb-2">
          <Button variant="outline" size="sm" asChild>
            <Link href={route('freshness.index', site.id)}>&larr; Back to Freshness</Link>
          </Button>
          <Button variant="default" size="sm" onClick={() => setIsGenerateBriefModalOpen(true)}>
            <FileText className="mr-2 h-4 w-4" />
            Generate Brief
          </Button>
        </div>

        <div className="flex items-center gap-3 mb-1">
          <h1 className="text-2xl font-bold tracking-tight">{recommendation.title}</h1>
          <Badge variant="secondary">{actionLabel(recommendation.action_type)}</Badge>
        </div>
        <p className="text-sm text-muted-foreground mb-6">{recommendation.page_url}</p>

        <div className="grid gap-6 lg:grid-cols-2">
          <div className="rounded-lg border bg-card p-4">
            <h2 className="text-lg font-semibold mb-3">Reasoning</h2>
            <p className="text-sm text-muted-foreground">{recommendation.reasoning}</p>

            <div className="mt-4 grid grid-cols-2 gap-4 text-sm">
              <div>
                <span className="text-muted-foreground">Impact: </span>
                <span className="font-medium">{recommendation.impact_score}/100</span>
              </div>
              <div>
                <span className="text-muted-foreground">Confidence: </span>
                <span className="font-medium">
                  {Math.round(recommendation.confidence_score * 100)}%
                </span>
              </div>
              <div>
                <span className="text-muted-foreground">Urgency: </span>
                <span className="font-medium">{recommendation.urgency_score}/100</span>
              </div>
              <div>
                <span className="text-muted-foreground">Effort: </span>
                <span className="font-medium">{recommendation.effort_score}/100</span>
              </div>
            </div>
          </div>

          <FreshnessScoreCard score={recommendation.freshness_score} />
        </div>

        {decaySignal && (
          <div className="mt-6 rounded-lg border bg-card p-4">
            <div className="flex items-center gap-3 mb-4">
              <h2 className="text-lg font-semibold">Decay Pattern</h2>
              <DecayPatternBadge pattern={decaySignal.decay_pattern_type} />
            </div>

            <div className="grid gap-6 md:grid-cols-2">
              <div>
                <h3 className="text-sm font-medium mb-3">Traffic History</h3>
                <dl className="grid gap-3 text-sm">
                  <div>
                    <dt className="text-muted-foreground">Baseline (90-day avg)</dt>
                    <dd className="font-medium">
                      {Math.round(decaySignal.baseline_90d_clicks)} clicks/day
                    </dd>
                  </div>
                  <div>
                    <dt className="text-muted-foreground">Baseline (28-day avg)</dt>
                    <dd className="font-medium">
                      {Math.round(decaySignal.baseline_28d_clicks)} clicks/day
                    </dd>
                  </div>
                  <div>
                    <dt className="text-muted-foreground">Baseline (7-day avg)</dt>
                    <dd className="font-medium">
                      {Math.round(decaySignal.baseline_7d_clicks)} clicks/day
                    </dd>
                  </div>
                  <div>
                    <dt className="text-muted-foreground">Current</dt>
                    <dd className="font-medium">
                      {Math.round(decaySignal.current_clicks)} clicks/day
                    </dd>
                  </div>
                </dl>
              </div>

              <div>
                <h3 className="text-sm font-medium mb-3">Decay Analysis</h3>
                <dl className="grid gap-3 text-sm">
                  <div>
                    <dt className="text-muted-foreground">Traffic Loss</dt>
                    <dd className="font-medium text-destructive">
                      {formatPercent(decaySignal.decay_magnitude / 100)}
                    </dd>
                  </div>
                  <div>
                    <dt className="text-muted-foreground">Pattern Confidence</dt>
                    <dd className="font-medium">
                      {Math.round(decaySignal.confidence_score * 100)}%
                    </dd>
                  </div>
                  <div>
                    <dt className="text-muted-foreground">Freshness Score</dt>
                    <dd className="font-medium">{decaySignal.freshness_score.toFixed(1)}/100</dd>
                  </div>
                </dl>
              </div>
            </div>

            {decaySignal.supporting_data && Object.keys(decaySignal.supporting_data).length > 0 && (
              <div className="mt-4 pt-4 border-t">
                <h3 className="text-sm font-medium mb-2">Supporting Evidence</h3>
                <div className="text-xs text-muted-foreground space-y-1">
                  {Object.entries(decaySignal.supporting_data).map(([key, value]) => (
                    <div key={key}>
                      <span className="font-medium">{key}: </span>
                      <span>{String(value)}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {wpPost && (
          <div className="mt-6 rounded-lg border bg-card p-4">
            <h2 className="text-lg font-semibold mb-3">Content Details</h2>
            <dl className="grid gap-3 text-sm sm:grid-cols-2 lg:grid-cols-4">
              <div>
                <dt className="text-muted-foreground">Title</dt>
                <dd className="font-medium">{wpPost.title}</dd>
              </div>
              {wpPost.wp_published_at && (
                <div>
                  <dt className="text-muted-foreground">Published</dt>
                  <dd className="font-medium">{formatDateOnly(wpPost.wp_published_at)}</dd>
                </div>
              )}
              {wpPost.wp_modified_at && (
                <div>
                  <dt className="text-muted-foreground">Last Modified</dt>
                  <dd className="font-medium">{formatDateOnly(wpPost.wp_modified_at)}</dd>
                </div>
              )}
              {wpPost.word_count != null && (
                <div>
                  <dt className="text-muted-foreground">Word Count</dt>
                  <dd className="font-medium">{wpPost.word_count}</dd>
                </div>
              )}
            </dl>
          </div>
        )}

        <div className="mt-6 rounded-lg border bg-card p-4">
          <h2 className="text-lg font-semibold mb-3">Analysis Period</h2>
          <dl className="grid gap-3 text-sm sm:grid-cols-3">
            <div>
              <dt className="text-muted-foreground">Window Start</dt>
              <dd className="font-medium">{decayRun.analysis_window_start}</dd>
            </div>
            <div>
              <dt className="text-muted-foreground">Window End</dt>
              <dd className="font-medium">{decayRun.analysis_window_end}</dd>
            </div>
            {decayRun.completed_at && (
              <div>
                <dt className="text-muted-foreground">Completed</dt>
                <dd className="font-medium">{formatDateOnly(decayRun.completed_at)}</dd>
              </div>
            )}
          </dl>
        </div>
      </div>

      {/* Generate Brief Modal */}
      <Dialog open={isGenerateBriefModalOpen} onOpenChange={setIsGenerateBriefModalOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Generate Content Brief</DialogTitle>
            <DialogDescription>
              Create a comprehensive content brief for this freshness recommendation using AI.
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleGenerateBrief} className="space-y-4">
            <div>
              <Label htmlFor="target_keyword">Target Keyword</Label>
              <Input
                id="target_keyword"
                type="text"
                value={data.target_keyword}
                onChange={(e) => setData('target_keyword', 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="custom_instructions">Custom Instructions (Optional)</Label>
              <Textarea
                id="custom_instructions"
                value={data.custom_instructions}
                onChange={(e) => setData('custom_instructions', e.target.value)}
                placeholder="Add any specific instructions for the brief (e.g., tone, audience, focus areas)"
                rows={4}
                className="mt-1"
              />
              {errors.custom_instructions && (
                <p className="text-sm text-destructive mt-1">{errors.custom_instructions}</p>
              )}
            </div>

            <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 bg-muted/50 p-3">
              <p className="text-sm font-medium mb-2">Estimated Cost:</p>
              <p className="text-xs text-muted-foreground">
                ~1,300 tokens (~$0.04 for GPT-4, ~$0.001 for GPT-3.5-turbo)
              </p>
            </div>

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

FreshnessShow.layout = (page: React.ReactNode) => <DashboardLayout>{page}</DashboardLayout>;
