
"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { MessageSquare, RefreshCw, ExternalLink } from "lucide-react"; // Using MessageSquare for WhatsApp context
import { suggestWhatsappQuestions, type SuggestWhatsappQuestionsInput, type SuggestWhatsappQuestionsOutput } from "@/ai/flows/dynamic-content-suggestions";
import { MOCK_AVAILABLE_CONTENT, MOCK_INDUSTRY_TRENDS, MOCK_USER_BEHAVIOR } from "@/constants";
import { Skeleton } from "@/components/ui/skeleton";
import Link from "next/link";

interface SuggestedQuestionItem {
  question: string;
}

export function DynamicContentSuggestions() {
  const [suggestedQuestions, setSuggestedQuestions] = useState<SuggestedQuestionItem[] | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchSuggestions = async () => {
    setIsLoading(true);
    setError(null);
    setSuggestedQuestions(null);

    try {
      const availableContentString = MOCK_AVAILABLE_CONTENT.map(
        (item) => `${item.type}: ${item.title} - ${item.description}`
      ).join("\n");

      const input: SuggestWhatsappQuestionsInput = {
        userBehavior: MOCK_USER_BEHAVIOR,
        industryTrends: MOCK_INDUSTRY_TRENDS,
        availableContent: availableContentString,
      };
      
      const result: SuggestWhatsappQuestionsOutput = await suggestWhatsappQuestions(input);
      setSuggestedQuestions(result.suggestedQuestions);
    } catch (err) {
      console.error("Error fetching content suggestions:", err);
      setError("Failed to load suggestions. Please try again.");
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchSuggestions();
  }, []);

  const renderSuggestions = () => {
    if (!suggestedQuestions || suggestedQuestions.length === 0) {
      return (
        <p className="text-muted-foreground text-sm">No specific questions available at the moment. Explore our site to discover more!</p>
      );
    }
    
    return (
      <ul className="space-y-4">
        {suggestedQuestions.map((item, index) => (
          <li key={index} className="p-4 border rounded-lg shadow-sm hover:shadow-md transition-shadow bg-card">
            <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
              <p className="text-md text-foreground flex-grow">{item.question}</p>
              <Button asChild size="sm" variant="outline" className="flex-shrink-0 w-full sm:w-auto">
                <Link 
                  href={`https://wa.me/?text=${encodeURIComponent(item.question)}`} 
                  target="_blank" 
                  rel="noopener noreferrer"
                  aria-label={`Ask this question on WhatsApp: ${item.question}`}
                >
                  Ask on WhatsApp
                  <ExternalLink className="ml-2 h-4 w-4" />
                </Link>
              </Button>
            </div>
          </li>
        ))}
      </ul>
    );
  };

  return (
    <Card className="shadow-lg">
      <CardHeader className="flex flex-row items-center justify-between">
        <div className="flex items-center">
          <MessageSquare className="h-6 w-6 text-primary mr-3" />
          <div>
            <CardTitle className="text-xl">Suggested Questions</CardTitle>
            <CardDescription>Tap a button to ask us on WhatsApp.</CardDescription>
          </div>
        </div>
        <Button variant="ghost" size="icon" onClick={fetchSuggestions} disabled={isLoading} aria-label="Refresh suggestions">
          <RefreshCw className={`h-5 w-5 ${isLoading ? 'animate-spin' : ''}`} />
        </Button>
      </CardHeader>
      <CardContent>
        {isLoading && (
          <div className="space-y-4">
            {[1, 2].map((_, i) => (
              <div key={i} className="p-4 border rounded-lg">
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
                  <Skeleton className="h-5 w-3/4" />
                  <Skeleton className="h-9 w-full sm:w-36" />
                </div>
              </div>
            ))}
          </div>
        )}
        {error && <p className="text-destructive text-sm">{error}</p>}
        {!isLoading && !error && renderSuggestions()}
      </CardContent>
    </Card>
  );
}
