"use client";

import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { generateAdSchema } from "@/lib/utils/validators";
import { Input } from "@/components/ui/Input";
import { Select } from "@/components/ui/Select";
import { Button } from "@/components/ui/Button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/Card";
import { IMAGE_MODELS, getModelCost, formatCost } from "@/lib/constants/models";
import type { Niche } from "@/types/api";
import { Loader2, TrendingUp, Check } from "lucide-react";
import apiClient from "@/lib/api/client";
import { InfoButton } from "@/components/ui/InfoButton";

interface GenerationFormProps {
  onSubmit: (data: { 
    niche: Niche; 
    num_images: number; 
    image_model?: string | null; 
    target_audience?: string | null; 
    offer?: string | null;
    use_trending?: boolean;
    trending_context?: string | null;
  }) => Promise<void>;
  isLoading: boolean;
}

interface TrendItem {
  title: string;
  description: string;
  url?: string;
  keyword?: string;
  relevance_score?: number;
}

export const GenerationForm: React.FC<GenerationFormProps> = ({
  onSubmit,
  isLoading,
}) => {
  const [trends, setTrends] = useState<TrendItem[]>([]);
  const [selectedTrend, setSelectedTrend] = useState<TrendItem | null>(null);
  const [isFetchingTrends, setIsFetchingTrends] = useState(false);
  const [trendsError, setTrendsError] = useState<string | null>(null);

  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    setValue,
  } = useForm({
    resolver: zodResolver(generateAdSchema),
    defaultValues: {
      niche: "home_insurance" as const,
      num_images: 1,
      image_model: null,
      target_audience: "",
      offer: "",
      use_trending: false,
      trending_context: "",
    },
  });

  const numImages = watch("num_images");
  const currentNiche = watch("niche");
  const useTrending = watch("use_trending");
  const selectedModel = watch("image_model");

  // Fetch trends when toggle is enabled
  const handleFetchTrends = async () => {
    setIsFetchingTrends(true);
    setTrendsError(null);
    setTrends([]);
    setSelectedTrend(null);

    try {
      const response = await apiClient.get(`/api/trends/${currentNiche}`);
      const data = response.data;
      
      if (data.trends && data.trends.length > 0) {
        setTrends(data.trends);
      } else {
        setTrendsError("No relevant trends found for this niche");
      }
    } catch (error: any) {
      setTrendsError(error.message || "Failed to fetch trends");
    } finally {
      setIsFetchingTrends(false);
    }
  };

  // Handle trend selection
  const handleSelectTrend = (trend: TrendItem) => {
    setSelectedTrend(trend);
    // Set the trending context with title and description
    const trendContext = `${trend.title} - ${trend.description}`;
    setValue("trending_context", trendContext);
  };

  // Reset trends when toggle is turned off
  React.useEffect(() => {
    if (!useTrending) {
      setTrends([]);
      setSelectedTrend(null);
      setTrendsError(null);
    }
  }, [useTrending]);

  return (
    <Card variant="glass">
      <CardHeader>
        <div className="flex items-center gap-2">
          <CardTitle>Generate Ad</CardTitle>
          <InfoButton
            title="Standard Generation Flow"
            content="This flow generates ads using randomized strategies from predefined angles and concepts. It's the fastest way to create ads with minimal configuration. The system automatically selects the best combinations based on your niche, target audience, and offer."
            position="bottom"
          />
        </div>
        <CardDescription>
          Create a new ad creative using randomized strategies
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          <Select
            label="Niche"
            options={[
              { value: "home_insurance", label: "Home Insurance" },
              { value: "glp1", label: "GLP-1" },
              { value: "auto_insurance", label: "Auto Insurance" },
            ]}
            error={errors.niche?.message}
            {...register("niche")}
          />

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Target Audience <span className="text-gray-400 font-normal">(Optional)</span>
            </label>
            <input
              type="text"
              className="w-full px-4 py-3 rounded-xl border-2 border-gray-300 bg-white/80 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-250"
              placeholder="e.g., US people over 50+ age"
              {...register("target_audience")}
            />
            {errors.target_audience && (
              <p className="text-red-500 text-xs mt-1">{errors.target_audience.message}</p>
            )}
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Offer <span className="text-gray-400 font-normal">(Optional)</span>
            </label>
            <input
              type="text"
              className="w-full px-4 py-3 rounded-xl border-2 border-gray-300 bg-white/80 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-250"
              placeholder="e.g., Don't overpay your insurance"
              {...register("offer")}
            />
            {errors.offer && (
              <p className="text-red-500 text-xs mt-1">{errors.offer.message}</p>
            )}
          </div>

          {/* Trending Topics – AI occasions + niche news; used in ad copy generation */}
          <div className="border-t border-gray-200 pt-4">
            <div className="flex items-center justify-between mb-3">
              <div>
                <label className="block text-sm font-semibold text-gray-700">
                  Use Trending Topics 🔥
                </label>
                <p className="text-xs text-gray-500 mt-1">
                  Tie your ad to current occasions and niche news for timeliness
                </p>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  className="sr-only peer"
                  {...register("use_trending")}
                />
                <div className="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:bg-blue-500 peer-focus:ring-2 peer-focus:ring-blue-300 transition-colors"></div>
              </label>
            </div>
            {useTrending && (
              <div className="mt-3 space-y-3 rounded-xl border border-gray-200 bg-gray-50/80 p-3">
                <Button
                  type="button"
                  variant="secondary"
                  size="sm"
                  onClick={handleFetchTrends}
                  disabled={isFetchingTrends}
                  className="gap-2"
                >
                  {isFetchingTrends ? <Loader2 className="h-4 w-4 animate-spin" /> : <TrendingUp className="h-4 w-4" />}
                  {isFetchingTrends ? "Fetching…" : "Fetch current trends"}
                </Button>
                {trendsError && <p className="text-sm text-red-600">{trendsError}</p>}
                {trends.length > 0 && (
                  <div className="space-y-2">
                    <p className="text-xs font-medium text-gray-600">Pick one (optional – otherwise we use the top trend):</p>
                    <div className="max-h-40 overflow-y-auto space-y-1.5">
                      {trends.map((trend) => (
                        <button
                          key={trend.title}
                          type="button"
                          onClick={() => handleSelectTrend(trend)}
                          className={`w-full text-left px-3 py-2 rounded-lg border text-sm transition-colors ${
                            selectedTrend?.title === trend.title
                              ? "border-blue-500 bg-blue-50 text-blue-800"
                              : "border-gray-200 bg-white hover:bg-gray-100"
                          }`}
                        >
                          <span className="font-medium">{trend.title}</span>
                          {selectedTrend?.title === trend.title && <Check className="inline h-4 w-4 ml-1 text-blue-600" />}
                          <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{trend.description}</p>
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>


          <Select
            label="Image Model"
            options={IMAGE_MODELS.map(model => ({ value: model.value, label: model.label }))}
            error={errors.image_model?.message}
            {...register("image_model")}
          />

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Number of Ad Images: <span className="text-blue-600 font-bold">{numImages}</span>
            </label>
            <input
              type="range"
              min="1"
              max="10"
              step="1"
              className="w-full accent-blue-500"
              {...register("num_images", { valueAsNumber: true })}
            />
            <div className="flex justify-between text-xs text-gray-500 mt-1 font-medium">
              <span>1</span>
              <span>10</span>
            </div>
            <p className="text-xs text-gray-500 mt-1">
              Generate multiple images for the same ad copy using the same method
            </p>
            {errors.num_images && (
              <p className="mt-1 text-sm text-red-600">
                {errors.num_images.message}
              </p>
            )}
          </div>

          {/* Cost Estimator */}
          <div className="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-xl p-4">
            <p className="text-sm font-semibold text-gray-800">
              💰 <strong>Estimated Cost:</strong> {formatCost(getModelCost(selectedModel || "", numImages))}
            </p>
            <p className="text-xs text-gray-600 mt-1">
              {numImages} image{numImages > 1 ? 's' : ''} × {IMAGE_MODELS.find(m => m.value === (selectedModel || ""))?.label.split(' - ')[0] || "Default model"}
            </p>
          </div>

          <Button
            type="submit"
            variant="primary"
            size="lg"
            isLoading={isLoading}
            className="w-full"
          >
            Generate Ad
          </Button>
        </form>
      </CardContent>
    </Card>
  );
};
