"use client";

import { useState, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import { useForm, Resolver, SubmitHandler, FieldValues } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { landingPageContentApi } from "@/lib/api";
import Link from "next/link";

const contentSchema = yup.object().shape({
  type: yup.string().oneOf(["carousel", "section", "content"]).required("Type is required"),
  title: yup.string().nullable(),
  content: yup.string().nullable(),
  imageUrl: yup.string().url("Must be a valid URL").nullable(),
  videoUrl: yup.string().url("Must be a valid URL").nullable(),
  linkUrl: yup.string().url("Must be a valid URL").nullable(),
  linkText: yup.string().nullable(),
  order: yup.number().required("Order is required").min(0),
  isActive: yup.boolean().default(true),
  metadata: yup.object().nullable(),
});

type ContentFormData = yup.InferType<typeof contentSchema>;

export default function EditLandingPageContent() {
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(true);

  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
  } = useForm<ContentFormData>({
    resolver: yupResolver(contentSchema) as Resolver<ContentFormData>,
    defaultValues: {
      type: "content",
      order: 0,
      isActive: true,
    },
  });

  const contentType = watch("type");

  useEffect(() => {
    if (id && id !== "new") {
      fetchContent();
    } else {
      setFetching(false);
    }
  }, [id]);

  const fetchContent = async () => {
    try {
      setFetching(true);
      const response = await landingPageContentApi.getById(Number.parseInt(id, 10));
      if (response.success) {
        const content = response.data;
        Object.keys(content).forEach((key) => {
          if (content[key] !== null && content[key] !== undefined) {
            setValue(key as keyof ContentFormData, content[key]);
          }
        });
      }
    } catch (error) {
      console.error("Error fetching content:", error);
      alert("Failed to load content");
    } finally {
      setFetching(false);
    }
  };

  const onSubmit: SubmitHandler<FieldValues> = async (rawData) => {
    const data = rawData as ContentFormData;
    try {
      setLoading(true);
      if (id && id !== "new") {
        await landingPageContentApi.update(Number.parseInt(id, 10), data);
      } else {
        await landingPageContentApi.create(data);
      }
      router.push("/landing-page");
    } catch (error) {
      console.error("Error saving content:", error);
      alert("Failed to save content");
    } finally {
      setLoading(false);
    }
  };

  if (fetching) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <p className="mt-2 text-gray-600">Loading content...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 p-8">
      <div className="max-w-4xl mx-auto">
        <div className="mb-6">
          <Link
            href="/landing-page"
            className="text-blue-600 hover:text-blue-800 mb-4 inline-block"
          >
            ← Back to Landing Page Management
          </Link>
          <h1 className="text-3xl font-bold text-gray-900 mt-2">
            {id === "new" ? "Add New Content" : "Edit Content"}
          </h1>
        </div>

        <form onSubmit={handleSubmit(onSubmit)} className="bg-white rounded-lg shadow-sm p-6 space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Type <span className="text-red-500">*</span>
              </label>
              <select
                {...register("type")}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900"
              >
                <option value="content">Content</option>
                <option value="carousel">Carousel</option>
                <option value="section">Section</option>
              </select>
              {errors.type && (
                <p className="mt-1 text-sm text-red-600">{errors.type.message}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Order <span className="text-red-500">*</span>
              </label>
              <input
                type="number"
                {...register("order")}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900"
              />
              {errors.order && (
                <p className="mt-1 text-sm text-red-600">{errors.order.message}</p>
              )}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Title</label>
            <input
              type="text"
              {...register("title")}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Content</label>
            <textarea
              {...register("content")}
              rows={6}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {(contentType === "carousel" || contentType === "section") && (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Image URL</label>
                <input
                  type="url"
                  {...register("imageUrl")}
                  placeholder="https://example.com/image.jpg"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900"
                />
                {errors.imageUrl && (
                  <p className="mt-1 text-sm text-red-600">{errors.imageUrl.message}</p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Video URL</label>
                <input
                  type="url"
                  {...register("videoUrl")}
                  placeholder="https://example.com/video.mp4"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900"
                />
                {errors.videoUrl && (
                  <p className="mt-1 text-sm text-red-600">{errors.videoUrl.message}</p>
                )}
              </div>
            </>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Link URL</label>
              <input
                type="url"
                {...register("linkUrl")}
                placeholder="https://example.com"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900"
              />
              {errors.linkUrl && (
                <p className="mt-1 text-sm text-red-600">{errors.linkUrl.message}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Link Text</label>
              <input
                type="text"
                {...register("linkText")}
                placeholder="Click here"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900"
              />
            </div>
          </div>

          <div className="flex items-center">
            <input
              type="checkbox"
              {...register("isActive")}
              className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
            <label className="ml-2 block text-sm text-gray-700">Active</label>
          </div>

          <div className="flex justify-end gap-4 pt-4">
            <Link
              href="/landing-page"
              className="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
            >
              Cancel
            </Link>
            <button
              type="submit"
              disabled={loading}
              className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {loading ? "Saving..." : id === "new" ? "Create Content" : "Update Content"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
