'use client';
import React, { useEffect, useState } from 'react';
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Loader2 } from "lucide-react";
import useSWR from 'swr';
import { APP_BASE_URL } from '@/utils/constants';
import { defaultFetcher, fetchHeader } from '@/helpers/fetch.helper';
import { CourseCategoryOptionHelper } from './CourseCategoryOptionHelper';
import BannerImageUpload from './BannerImageUpload';
import { useToast } from '@/hooks/use-toast';
import { useRouter } from 'next/navigation';
import { routes } from '@/lib/routes';

const CourseActionFormTabContent: React.FC = () => {
    // Fetch categories
    const { toast } = useToast();
    const router = useRouter()
    const { data: CategoryOption } = useSWR(APP_BASE_URL + '/api/course/getCategories', defaultFetcher);
    
    // Form state
    const [formData, setFormData] = useState({
        course_name: '',
        category_uuid: '',
        course_description: '',
        page_for_community: '',
        course_pdf: null as File | null ,
        cover_image : null as File | null
    });

    // UI states
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [errors, setErrors] = useState<Record<string, string>>({});
    const [submitStatus, setSubmitStatus] = useState<{
        type: 'success' | 'error' | null;
        message: string;
    }>({ type: null, message: '' });
    
    const [categoryOptions, setCategoryOptions] = useState<any>([]);

    // Update category options when data is fetched
    useEffect(() => {
        CategoryOption && setCategoryOptions(CourseCategoryOptionHelper(CategoryOption));
    }, [CategoryOption]);

    // Handle input changes
    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
        // Clear error when user types
        if (errors[name]) {
            setErrors(prev => ({
                ...prev,
                [name]: ''
            }));
        }
    };

    // Handle select change
    const handleSelectChange = (value: string) => {
        console.log(value)
        setFormData(prev => ({
            ...prev,
            category_uuid: value
        }));
        
    };

    // Handle file change
    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0] || null;
        setFormData(prev => ({
            ...prev,
            coursePdf: file
        }));
        if (errors.coursePdf) {
            setErrors(prev => ({
                ...prev,
                coursePdf: ''
            }));
        }
    };

    // Validate form

    // Handle form submission
    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        

        setIsSubmitting(true);
        setSubmitStatus({ type: null, message: '' });

        try {
            // Create FormData for file upload
            const submitFormData = new FormData();
            Object.entries(formData).forEach(([key, value]) => {
                if (value !== null) {
                    submitFormData.append(key, value);
                }
            });
            // Make API call
            const response = await fetch(`${APP_BASE_URL}/api/course/createCourse`, {
                headers : fetchHeader(),
                method: 'POST',
                body: submitFormData
            });

            if (!response.ok) {
                toast({
                    title : 'Failed to completete Task !' ,
                    description : 'Something went wrong creating course' ,
                    variant : 'destructive'
                })
                return;
            }

            const data : any = await response.json();
            
            // Show success message
            toast({
                title : 'SuccessFul !' ,
                description : `${data?.message}` ,
                variant : 'success'
            })

            // Reset form
            setFormData({
                course_name: '',
                category_uuid: '',
                course_description: '',
                page_for_community: '',
                course_pdf: null , 
                cover_image : null
            });
            
            // Reset file input
            const fileInput = document.getElementById('coursePdf') as HTMLInputElement;
            if (fileInput) fileInput.value = '';
            router.push(routes.MY_COURSES_INDEX)

        } catch (error) {
            
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleImageChange = (file: File | null) => {
        setFormData((prev) => ({...prev , banner_image : file}))
    }

    return (
        <Card className='border border-purple-700/20 shadow shadow-purple-700/40'>
            <CardHeader>
                <CardTitle className="text-2xl text-purple-700">Create New Course</CardTitle>
            </CardHeader>
            <CardContent>

                <form onSubmit={handleSubmit} className="grid grid-cols-2 gap-6">

                    <BannerImageUpload
                        onImageChange={handleImageChange}
                        defaultImage={formData?.cover_image as string}
                        maxSizeMB={2}
                    />
                    {/* Course Title */}
                    <div className="space-y-2">
                        <Label htmlFor="course_name">Course Name</Label>
                        <Input
                            id="course_name"
                            name="course_name"
                            value={formData.course_name}
                            onChange={handleChange}
                            placeholder="Enter course name"
                            className={`w-full ${errors.course_name ? 'border-red-500' : ''}`}
                        />
                        {errors.course_name && (
                            <p className="text-sm text-red-500">{errors.course_name}</p>
                        )}
                    </div>

                    {/* Course Category */}
                    <div className="space-y-2">
                        <Label htmlFor="category_uuid">Category</Label>
                        <Select 
                            name="category_uuid" 
                            value={formData.category_uuid}
                            onValueChange={handleSelectChange}
                        >
                            <SelectTrigger className={errors.category_uuid ? 'border-red-500' : ''}>
                                <SelectValue placeholder="Select a category" />
                            </SelectTrigger>
                            <SelectContent>
                                {categoryOptions?.map((categoryOption: any, index: number) => (
                                    <SelectItem 
                                        value={categoryOption?.value} 
                                        key={index}
                                    >
                                        {categoryOption?.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        {errors?.category && (
                            <p className="text-sm text-red-500">{errors.category}</p>
                        )}
                    </div>

                    <div className="space-y-2">
                        <Label htmlFor="coursePdf">Course PDF</Label>
                        <Input
                            id="course_pdf"
                            name="course_pdf"
                            type="file"
                            accept=".pdf"
                            onChange={handleFileChange}
                            className={`cursor-pointer ${errors.course_pdf ? 'border-red-500' : ''}`}
                        />
                        {errors?.coursePdf && (
                            <p className="text-sm text-red-500">{errors.coursePdf}</p>
                        )}
                    </div>
                    {/* Required Pages */}
                    <div className="space-y-2">
                        <Label htmlFor="requiredPages">Required Pages for Discussion Joining ?</Label>
                        <Input
                            id="page_for_community"
                            name="page_for_community"
                            type="number"
                            value={formData?.page_for_community}
                            onChange={handleChange}
                            min="1"
                            placeholder="Enter number of required pages"
                            className={errors.page_for_community ? 'border-red-500' : ''}
                        />
                        {errors.page_for_community && (
                            <p className="text-sm text-red-500">{errors.page_for_community}</p>
                        )}
                    </div>

                    {/* Course Description */}
                    <div className="space-y-2 col-span-2">
                        <Label htmlFor="description">Description</Label>
                        <Textarea
                            id="course_description"
                            name="course_description"
                            value={formData?.course_description}
                            onChange={handleChange}
                            placeholder="Enter course course_description"
                            className={`min-h-32 ${errors.course_description ? 'border-red-500' : ''}`}
                        />
                        {errors.course_description && (
                            <p className="text-sm text-red-500">{errors.course_description}</p>
                        )}
                    </div>

                    

                    

                    {/* PDF Upload */}
                    

                    {/* Submit Button */}
                    <div className="mx-auto w-fit col-span-2">
                        <Button 
                            type="submit"
                            className="mt-6 w-full md:min-w-[400px] min-w-[300px] bg-purple-700"
                            disabled={isSubmitting}
                        >
                            {isSubmitting ? (
                                <>
                                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                    Creating Course...
                                </>
                            ) : (
                                'Save Changes'
                            )}
                        </Button>
                    </div>
                </form>
            </CardContent>
        </Card>
    );
};

export default CourseActionFormTabContent;