'use client';

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';

import Button, { ButtonSize, ButtonVariant } from '@/components/button/Button';
import { FaqAnswerMarkdown } from '@/components/contest/FaqAnswerMarkdown';
import { toast } from '@/components/toast/Toast';
import { useApiClient } from '@/lib/apiClient';
import type { components } from '@/lib/gen';

type ContestInfoSchema = components['schemas']['ContestInfoSchema'];
type ContestVisibility = components['schemas']['ContestVisibility'];
type FAQItemSchema = components['schemas']['FAQItemSchema'];

interface SectionVisibility {
  hero: ContestVisibility;
  remix_cta: ContestVisibility;
  submissions: ContestVisibility;
  video_highlight: ContestVisibility;
  faq: ContestVisibility;
}

const DEFAULT_SECTION_VISIBILITY: SectionVisibility = {
  hero: 'everyone',
  remix_cta: 'everyone',
  submissions: 'staff',
  video_highlight: 'none',
  faq: 'everyone',
};

interface ContestInfoSectionProps {
  contestId: string;
}

export default function ContestInfoSection({
  contestId,
}: ContestInfoSectionProps) {
  const apiClient = useApiClient();
  const queryClient = useQueryClient();

  const [formData, setFormData] = useState({
    // Hero content
    hero_title: '',
    hero_description: '',
    hero_background_image: '',
    hero_background_image_mobile: '',
    hero_background_image_video: '',
    hero_background_image_video_mobile: '',

    // Remix CTA
    remix_cta_deadline_text: '',
    remix_cta_headline_text: '',
    remix_cta_subheader_text: '',
    remix_cta_remix_label: '',

    // Video highlight
    video_highlight_headline_text: '',
    video_highlight_subheader_text: '',
    video_highlight_video: '',
    video_highlight_video_mobile: '',
  });

  const [sectionVisibility, setSectionVisibility] = useState<SectionVisibility>(
    DEFAULT_SECTION_VISIBILITY
  );

  const [faqItems, setFaqItems] = useState<FAQItemSchema[]>([]);

  // Fetch contest info
  const { data: contestInfo, isLoading } = useQuery({
    queryKey: ['contest-info', contestId],
    queryFn: async () => {
      const { data } = await apiClient.GET(
        '/api/contests/contest/{contest_identifier}/info',
        {
          params: { path: { contest_identifier: contestId } },
        }
      );
      return data as ContestInfoSchema;
    },
    staleTime: 30_000,
  });

  // Populate form when contest info loads
  useEffect(() => {
    if (contestInfo) {
      setFormData({
        hero_title: contestInfo.hero_title || '',
        hero_description: contestInfo.hero_description || '',
        hero_background_image: contestInfo.hero_background_image || '',
        hero_background_image_mobile:
          contestInfo.hero_background_image_mobile || '',
        hero_background_image_video:
          contestInfo.hero_background_image_video || '',
        hero_background_image_video_mobile:
          contestInfo.hero_background_image_video_mobile || '',
        remix_cta_deadline_text: contestInfo.remix_cta_deadline_text || '',
        remix_cta_headline_text: contestInfo.remix_cta_headline_text || '',
        remix_cta_subheader_text: contestInfo.remix_cta_subheader_text || '',
        remix_cta_remix_label: contestInfo.remix_cta_remix_label || '',
        video_highlight_headline_text:
          contestInfo.video_highlight_headline_text || '',
        video_highlight_subheader_text:
          contestInfo.video_highlight_subheader_text || '',
        video_highlight_video: contestInfo.video_highlight_video || '',
        video_highlight_video_mobile:
          contestInfo.video_highlight_video_mobile || '',
      });

      if (contestInfo.landing_page_sections_visibility) {
        setSectionVisibility(
          contestInfo.landing_page_sections_visibility as unknown as SectionVisibility
        );
      }

      if (contestInfo.faq_questions) {
        setFaqItems(contestInfo.faq_questions);
      }
    }
  }, [contestInfo]);

  // Update mutation
  const updateMutation = useMutation({
    mutationFn: async (data: Partial<ContestInfoSchema>) => {
      const { data: responseData, error } = await apiClient.PUT(
        '/api/contests/contest/{contest_identifier}/info',
        {
          params: { path: { contest_identifier: contestId } },
          body: data as ContestInfoSchema,
        }
      );
      if (error) {
        console.error('Contest info update error:', error);
        throw new Error('Failed to update contest info');
      }
      return responseData;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contest-info', contestId] });
      toast({
        title: 'Contest info updated successfully!',
        status: 'success',
        duration: 2500,
        isClosable: true,
      });
    },
    onError: (error) => {
      console.error('Contest info update mutation error:', error);
      toast({
        title: 'Failed to update contest info',
        description: error instanceof Error ? error.message : undefined,
        status: 'error',
        isClosable: true,
      });
    },
  });

  const handleSave = () => {
    const dataToSave: Partial<ContestInfoSchema> = {
      ...formData,
      landing_page_sections_visibility: sectionVisibility as unknown as Record<
        string,
        ContestVisibility
      >,
      faq_questions: faqItems.filter((item) => item.question || item.answer),
    };

    updateMutation.mutate(dataToSave);
  };

  const addFaqItem = () => {
    setFaqItems([...faqItems, { question: '', answer: '' }]);
  };

  const updateFaqItem = (
    index: number,
    field: 'question' | 'answer',
    value: string
  ) => {
    const newItems = [...faqItems];
    newItems[index] = { ...newItems[index], [field]: value };
    setFaqItems(newItems);
  };

  const removeFaqItem = (index: number) => {
    setFaqItems(faqItems.filter((_, i) => i !== index));
  };

  if (isLoading) {
    return (
      <div className='rounded-lg border border-border-primary bg-background-secondary p-6'>
        <div className='text-foreground-secondary'>Loading contest info...</div>
      </div>
    );
  }

  return (
    <div className='rounded-lg border border-border-primary bg-background-secondary p-6'>
      <h3 className='mb-4 text-lg font-semibold text-foreground-primary'>
        Landing Page Content
      </h3>

      <div className='space-y-6'>
        {/* Hero Section */}
        <div className='border-t border-border-secondary pt-4'>
          <h4 className='text-md mb-3 font-medium text-foreground-primary'>
            Hero Section
          </h4>
          <div className='space-y-3'>
            <div>
              <label
                htmlFor='hero_title'
                className='mb-2 block text-sm font-medium text-foreground-primary'
              >
                Hero Title *
              </label>
              <input
                id='hero_title'
                type='text'
                value={formData.hero_title}
                onChange={(e) =>
                  setFormData({ ...formData, hero_title: e.target.value })
                }
                className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                placeholder='e.g., Summer Music Challenge'
              />
            </div>
            <div>
              <label
                htmlFor='hero_description'
                className='mb-2 block text-sm font-medium text-foreground-primary'
              >
                Hero Description *
              </label>
              <textarea
                id='hero_description'
                rows={3}
                value={formData.hero_description}
                onChange={(e) =>
                  setFormData({ ...formData, hero_description: e.target.value })
                }
                className='w-full resize-none rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                placeholder='Describe what makes this contest special...'
              />
            </div>
            <div className='grid grid-cols-2 gap-3'>
              <div>
                <label
                  htmlFor='hero_background_image'
                  className='mb-2 block text-sm font-medium text-foreground-primary'
                >
                  Background Image URL (Desktop)
                </label>
                <input
                  id='hero_background_image'
                  type='url'
                  value={formData.hero_background_image}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      hero_background_image: e.target.value,
                    })
                  }
                  className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                  placeholder='https://...'
                />
              </div>
              <div>
                <label
                  htmlFor='hero_background_image_mobile'
                  className='mb-2 block text-sm font-medium text-foreground-primary'
                >
                  Background Image URL (Mobile)
                </label>
                <input
                  id='hero_background_image_mobile'
                  type='url'
                  value={formData.hero_background_image_mobile}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      hero_background_image_mobile: e.target.value,
                    })
                  }
                  className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                  placeholder='https://...'
                />
              </div>
            </div>
            <div className='grid grid-cols-2 gap-3'>
              <div>
                <label
                  htmlFor='hero_background_video'
                  className='mb-2 block text-sm font-medium text-foreground-primary'
                >
                  Background Video URL (Desktop)
                </label>
                <input
                  id='hero_background_video'
                  type='url'
                  value={formData.hero_background_image_video}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      hero_background_image_video: e.target.value,
                    })
                  }
                  className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                  placeholder='https://...'
                />
              </div>
              <div>
                <label
                  htmlFor='hero_background_video_mobile'
                  className='mb-2 block text-sm font-medium text-foreground-primary'
                >
                  Background Video URL (Mobile)
                </label>
                <input
                  id='hero_background_video_mobile'
                  type='url'
                  value={formData.hero_background_image_video_mobile}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      hero_background_image_video_mobile: e.target.value,
                    })
                  }
                  className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                  placeholder='https://...'
                />
              </div>
            </div>
          </div>
        </div>

        {/* Remix CTA Section */}
        <div className='border-t border-border-secondary pt-4'>
          <h4 className='text-md mb-3 font-medium text-foreground-primary'>
            Remix CTA Section
          </h4>
          <div className='space-y-3'>
            <div className='grid grid-cols-2 gap-3'>
              <div>
                <label
                  htmlFor='remix_cta_deadline'
                  className='mb-2 block text-sm font-medium text-foreground-primary'
                >
                  Deadline Text
                </label>
                <input
                  id='remix_cta_deadline'
                  type='text'
                  value={formData.remix_cta_deadline_text}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      remix_cta_deadline_text: e.target.value,
                    })
                  }
                  className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                  placeholder='e.g., Submissions close Dec 31'
                />
              </div>
              <div>
                <label
                  htmlFor='remix_cta_label'
                  className='mb-2 block text-sm font-medium text-foreground-primary'
                >
                  Remix Button Label
                </label>
                <input
                  id='remix_cta_label'
                  type='text'
                  value={formData.remix_cta_remix_label}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      remix_cta_remix_label: e.target.value,
                    })
                  }
                  className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                  placeholder='e.g., Remix Now'
                />
              </div>
            </div>
            <div>
              <label
                htmlFor='remix_cta_headline'
                className='mb-2 block text-sm font-medium text-foreground-primary'
              >
                Headline
              </label>
              <input
                id='remix_cta_headline'
                type='text'
                value={formData.remix_cta_headline_text}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    remix_cta_headline_text: e.target.value,
                  })
                }
                className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                placeholder='e.g., Create Your Own Remix'
              />
            </div>
            <div>
              <label
                htmlFor='remix_cta_subheader'
                className='mb-2 block text-sm font-medium text-foreground-primary'
              >
                Subheader
              </label>
              <textarea
                id='remix_cta_subheader'
                rows={2}
                value={formData.remix_cta_subheader_text}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    remix_cta_subheader_text: e.target.value,
                  })
                }
                className='w-full resize-none rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                placeholder='Additional details about the contest...'
              />
            </div>
          </div>
        </div>

        {/* Video Highlight Section */}
        <div className='border-t border-border-secondary pt-4'>
          <h4 className='text-md mb-3 font-medium text-foreground-primary'>
            Video Highlight Section
          </h4>
          <div className='space-y-3'>
            <div className='grid grid-cols-2 gap-3'>
              <div>
                <label
                  htmlFor='video_highlight_headline'
                  className='mb-2 block text-sm font-medium text-foreground-primary'
                >
                  Headline
                </label>
                <input
                  id='video_highlight_headline'
                  type='text'
                  value={formData.video_highlight_headline_text}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      video_highlight_headline_text: e.target.value,
                    })
                  }
                  className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                  placeholder='Video section title'
                />
              </div>
              <div>
                <label
                  htmlFor='video_highlight_subheader'
                  className='mb-2 block text-sm font-medium text-foreground-primary'
                >
                  Subheader
                </label>
                <input
                  id='video_highlight_subheader'
                  type='text'
                  value={formData.video_highlight_subheader_text}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      video_highlight_subheader_text: e.target.value,
                    })
                  }
                  className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                  placeholder='Video description'
                />
              </div>
            </div>
            <div className='grid grid-cols-2 gap-3'>
              <div>
                <label
                  htmlFor='video_highlight_url'
                  className='mb-2 block text-sm font-medium text-foreground-primary'
                >
                  Video URL (Desktop)
                </label>
                <input
                  id='video_highlight_url'
                  type='url'
                  value={formData.video_highlight_video}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      video_highlight_video: e.target.value,
                    })
                  }
                  className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                  placeholder='https://... (video or Twitch URL)'
                />
              </div>
              <div>
                <label
                  htmlFor='video_highlight_url_mobile'
                  className='mb-2 block text-sm font-medium text-foreground-primary'
                >
                  Video URL (Mobile)
                </label>
                <input
                  id='video_highlight_url_mobile'
                  type='url'
                  value={formData.video_highlight_video_mobile}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      video_highlight_video_mobile: e.target.value,
                    })
                  }
                  className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                  placeholder='https://... (video or Twitch URL)'
                />
              </div>
            </div>
          </div>
        </div>

        {/* Section Visibility */}
        <div className='border-t border-border-secondary pt-4'>
          <h4 className='text-md mb-3 font-medium text-foreground-primary'>
            Section Visibility
          </h4>
          <div className='grid grid-cols-2 gap-3'>
            {(
              Object.keys(DEFAULT_SECTION_VISIBILITY) as Array<
                keyof SectionVisibility
              >
            ).map((section) => (
              <div key={section}>
                <label className='mb-2 block text-sm font-medium text-foreground-primary capitalize'>
                  {section.replace('_', ' ')}
                </label>
                <select
                  value={sectionVisibility[section]}
                  onChange={(e) =>
                    setSectionVisibility({
                      ...sectionVisibility,
                      [section]: e.target.value as ContestVisibility,
                    })
                  }
                  className='w-full rounded-lg border border-border-secondary bg-background-primary px-4 py-2.5 text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                >
                  <option value='everyone'>Everyone</option>
                  <option value='staff'>Staff Only</option>
                  <option value='none'>Hidden</option>
                </select>
              </div>
            ))}
          </div>
        </div>

        {/* FAQ Section */}
        <div className='border-t border-border-secondary pt-4'>
          <div className='mb-3 flex items-center justify-between'>
            <h4 className='text-md font-medium text-foreground-primary'>
              FAQ Items
            </h4>
            <Button
              onClick={addFaqItem}
              variant={ButtonVariant.Primary}
              size={ButtonSize.Small}
            >
              + Add FAQ
            </Button>
          </div>
          <div className='space-y-3'>
            {faqItems.map((item, index) => (
              <div
                key={index}
                className='rounded-lg border border-border-secondary bg-background-primary p-3'
              >
                <div className='mb-2 flex items-start justify-between gap-3'>
                  <div className='flex-1 space-y-2'>
                    <input
                      type='text'
                      value={item.question}
                      onChange={(e) =>
                        updateFaqItem(index, 'question', e.target.value)
                      }
                      placeholder='Question'
                      className='w-full rounded-lg border border-border-secondary bg-background-secondary px-3 py-2 text-sm text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                    />
                    <textarea
                      rows={5}
                      value={item.answer}
                      onChange={(e) =>
                        updateFaqItem(index, 'answer', e.target.value)
                      }
                      placeholder='Answer (supports Markdown formatting)'
                      className='w-full resize-none rounded-lg border border-border-secondary bg-background-secondary px-3 py-2 text-sm text-foreground-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none'
                    />
                    {item.answer && (
                      <div className='mt-2 rounded-lg border border-border-primary bg-background-secondary p-3'>
                        <p className='mb-2 text-xs font-medium text-foreground-secondary'>
                          Formatted Answer Preview:
                        </p>
                        <FaqAnswerMarkdown
                          answer={item.answer}
                          className='text-foreground-secondary'
                        />
                      </div>
                    )}
                  </div>
                  <Button
                    onClick={() => removeFaqItem(index)}
                    variant={ButtonVariant.Tertiary}
                    size={ButtonSize.Small}
                    className='text-red-600 dark:text-red-400'
                  >
                    Remove
                  </Button>
                </div>
              </div>
            ))}
            {faqItems.length === 0 && (
              <div className='py-4 text-center text-sm text-foreground-secondary'>
                No FAQ items yet. Click "Add FAQ" to create one.
              </div>
            )}
          </div>
        </div>

        {/* Save Button */}
        <div className='border-t border-border-secondary pt-4'>
          <Button
            onClick={handleSave}
            disabled={updateMutation.isPending}
            variant={ButtonVariant.Primary}
            size={ButtonSize.Large}
          >
            {updateMutation.isPending
              ? 'Saving...'
              : 'Save Landing Page Content'}
          </Button>
        </div>
      </div>
    </div>
  );
}
