import { PageLayout } from "@/components/layout/PageLayout";
import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { queryClient, apiRequest } from "@/lib/queryClient";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Author } from "@shared/schema";
import { insertTranslationSchema } from "@shared/schema";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { useToast } from "@/hooks/use-toast";
import { Check, CircleAlert, Loader2 } from "lucide-react";
import { LineNumberedText } from "@/components/reading/LineNumberedText";

// Extended validation schema based on the base insertTranslationSchema
const submitTranslationSchema = insertTranslationSchema.extend({
  // Additional fields for form validation
  acknowledgment: z.boolean().refine(val => val === true, {
    message: "You must acknowledge that you have the rights to submit this translation",
  }),
  // Terms and conditions
  terms: z.boolean().refine(val => val === true, {
    message: "You must agree to the terms and conditions",
  }),
});

type SubmissionType = 'translation' | 'original';

export default function Submit() {
  const [submissionType, setSubmissionType] = useState<SubmissionType>('translation');
  const [currentStep, setCurrentStep] = useState(1);
  const [originalWork, setOriginalWork] = useState<any>(null);
  const [previewMode, setPreviewMode] = useState(false);
  const { toast } = useToast();

  // Fetch authors for dropdown
  const { data: authors, isLoading: authorsLoading } = useQuery<Author[]>({
    queryKey: ['/api/authors'],
  });

  // Fetch works when an author is selected
  const { data: works, isLoading: worksLoading } = useQuery({
    queryKey: ['/api/authors/works', form.watch('workId')],
    enabled: !!form.watch('workId'),
  });

  // Form for translation submission
  const form = useForm<z.infer<typeof submitTranslationSchema>>({
    resolver: zodResolver(submitTranslationSchema),
    defaultValues: {
      workId: 0,
      title: "",
      language: "",
      content: "",
      translatorId: 1, // Using demo user ID
      year: new Date().getFullYear(),
      notes: "",
      acknowledgment: false,
      terms: false
    },
  });

  // Mutation for submitting the translation
  const mutation = useMutation({
    mutationFn: async (values: z.infer<typeof submitTranslationSchema>) => {
      // Remove additional form fields not in the API schema
      const { acknowledgment, terms, ...submissionData } = values;
      return await apiRequest('POST', '/api/translations', submissionData);
    },
    onSuccess: () => {
      toast({
        title: "Success!",
        description: "Your translation has been submitted for review",
      });
      queryClient.invalidateQueries({ queryKey: ['/api/translations'] });
      // Reset form and go back to step 1
      form.reset();
      setCurrentStep(1);
      setPreviewMode(false);
    },
    onError: (error) => {
      toast({
        title: "Error",
        description: `Failed to submit translation: ${error.message}`,
        variant: "destructive",
      });
    },
  });

  // Function to handle form submission
  const onSubmit = (values: z.infer<typeof submitTranslationSchema>) => {
    if (currentStep < 4) {
      // Move to next step
      setCurrentStep(currentStep + 1);
    } else {
      // Final submission
      mutation.mutate(values);
    }
  };

  // Function to go back to previous step
  const handleBack = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  // Function to fetch original work details when selected
  const handleWorkSelect = async (workId: number) => {
    if (workId) {
      try {
        const response = await fetch(`/api/works/${workId}`);
        if (response.ok) {
          const data = await response.json();
          setOriginalWork(data);
          
          // Pre-fill the title based on original work
          form.setValue('title', data.title);
        }
      } catch (error) {
        console.error('Error fetching work details:', error);
      }
    } else {
      setOriginalWork(null);
    }
  };

  return (
    <PageLayout>
      <div className="max-w-[var(--content-width)] mx-auto px-4 md:px-6 py-8">
        <div className="mb-8 text-center">
          <h1 className="text-2xl md:text-3xl font-bold font-serif text-navy dark:text-cream mb-2">
            Contribute to Tercul
          </h1>
          <p className="text-navy/70 dark:text-cream/70 max-w-2xl mx-auto">
            Share translations of literary works with readers around the world. 
            Your contributions help preserve and spread literary heritage across languages.
          </p>
        </div>

        <Card className="bg-cream dark:bg-dark-surface mb-8">
          <CardHeader>
            <CardTitle className="font-serif">Choose Contribution Type</CardTitle>
            <CardDescription>
              Select whether you're submitting a new translation or an original work
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Tabs defaultValue="translation" onValueChange={(value) => setSubmissionType(value as SubmissionType)}>
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="translation">Translation</TabsTrigger>
                <TabsTrigger value="original">Original Work</TabsTrigger>
              </TabsList>
              <TabsContent value="translation" className="pt-4">
                <p className="text-navy/80 dark:text-cream/80 mb-2">
                  Submit a translation of an existing work in the Tercul library. 
                  You'll need to select the original work and provide your translation.
                </p>
              </TabsContent>
              <TabsContent value="original" className="pt-4">
                <p className="text-navy/80 dark:text-cream/80 mb-2">
                  Submit an original work not yet in the Tercul library. 
                  This feature is coming soon!
                </p>
                <div className="flex items-center p-4 bg-navy/10 dark:bg-navy/20 rounded-lg mt-2">
                  <CircleAlert className="h-5 w-5 text-navy/70 dark:text-cream/70 mr-2" />
                  <p className="text-sm text-navy/70 dark:text-cream/70">
                    Original work submission is currently under development. 
                    Please check back later or contact us to submit original works.
                  </p>
                </div>
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>

        {/* Submission Wizard */}
        {submissionType === 'translation' && (
          <div className="space-y-8">
            {/* Progress indicators */}
            <div className="mb-8">
              <div className="flex justify-between mb-2">
                <span className="text-sm text-navy/70 dark:text-cream/70">Step {currentStep} of 4</span>
                <span className="text-sm text-navy/70 dark:text-cream/70">{Math.round((currentStep / 4) * 100)}% Complete</span>
              </div>
              <Progress value={(currentStep / 4) * 100} className="h-2" />
            </div>

            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
                {/* Step 1: Select Original Work */}
                {currentStep === 1 && (
                  <div className="space-y-6">
                    <h2 className="text-lg font-serif font-semibold text-navy dark:text-cream">
                      Select the original work
                    </h2>

                    <FormField
                      control={form.control}
                      name="workId"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Author</FormLabel>
                          <Select
                            disabled={authorsLoading}
                            onValueChange={(value) => {
                              // This would need to be updated to fetch works by author
                              // For now, it's a placeholder
                            }}
                          >
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="Select author" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {authorsLoading ? (
                                <SelectItem value="loading" disabled>Loading authors...</SelectItem>
                              ) : authors && authors.length > 0 ? (
                                authors.map((author) => (
                                  <SelectItem key={author.id} value={author.id.toString()}>
                                    {author.name}
                                  </SelectItem>
                                ))
                              ) : (
                                <SelectItem value="empty" disabled>No authors found</SelectItem>
                              )}
                            </SelectContent>
                          </Select>
                          <FormDescription>
                            Select the author of the original work
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="workId"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Original Work</FormLabel>
                          <Select
                            disabled={!form.watch('workId') || worksLoading}
                            onValueChange={(value) => {
                              field.onChange(parseInt(value, 10));
                              handleWorkSelect(parseInt(value, 10));
                            }}
                            value={field.value ? field.value.toString() : undefined}
                          >
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="Select work" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              {worksLoading ? (
                                <SelectItem value="loading" disabled>Loading works...</SelectItem>
                              ) : works && works.length > 0 ? (
                                works.map((work: any) => (
                                  <SelectItem key={work.id} value={work.id.toString()}>
                                    {work.title}
                                  </SelectItem>
                                ))
                              ) : (
                                <SelectItem value="empty" disabled>
                                  {form.watch('workId') ? "No works found for this author" : "Select an author first"}
                                </SelectItem>
                              )}
                            </SelectContent>
                          </Select>
                          <FormDescription>
                            Select the original work you're translating
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    {originalWork && (
                      <div className="mt-4 p-4 border border-sage/20 dark:border-sage/10 rounded-lg bg-paper dark:bg-dark-paper">
                        <h3 className="font-medium mb-2">Original Work Preview</h3>
                        <p className="text-sm text-navy/70 dark:text-cream/70 mb-2">
                          Language: {originalWork.language} • Published: {originalWork.year || 'Unknown'}
                        </p>
                        <div className="max-h-40 overflow-y-auto border border-sage/20 dark:border-sage/10 rounded p-3 bg-cream dark:bg-dark-surface">
                          <p className="text-sm whitespace-pre-line">{originalWork.content.substring(0, 300)}...</p>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* Step 2: Translation Details */}
                {currentStep === 2 && (
                  <div className="space-y-6">
                    <h2 className="text-lg font-serif font-semibold text-navy dark:text-cream">
                      Translation Details
                    </h2>

                    <FormField
                      control={form.control}
                      name="title"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Translation Title</FormLabel>
                          <FormControl>
                            <Input placeholder="Enter the title of your translation" {...field} />
                          </FormControl>
                          <FormDescription>
                            You can use the original title or provide a translated title
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="language"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Target Language</FormLabel>
                          <Select
                            onValueChange={field.onChange}
                            value={field.value}
                          >
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="Select language" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="English">English</SelectItem>
                              <SelectItem value="French">French</SelectItem>
                              <SelectItem value="German">German</SelectItem>
                              <SelectItem value="Spanish">Spanish</SelectItem>
                              <SelectItem value="Italian">Italian</SelectItem>
                              <SelectItem value="Russian">Russian</SelectItem>
                              <SelectItem value="Chinese">Chinese</SelectItem>
                              <SelectItem value="Japanese">Japanese</SelectItem>
                            </SelectContent>
                          </Select>
                          <FormDescription>
                            The language you're translating into
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="year"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Year of Translation</FormLabel>
                          <FormControl>
                            <Input 
                              type="number" 
                              min="1800" 
                              max={new Date().getFullYear()}
                              placeholder="Enter year" 
                              {...field}
                              onChange={e => field.onChange(parseInt(e.target.value, 10))} 
                            />
                          </FormControl>
                          <FormDescription>
                            When was this translation created
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                )}

                {/* Step 3: Translation Content */}
                {currentStep === 3 && (
                  <div className="space-y-6">
                    <h2 className="text-lg font-serif font-semibold text-navy dark:text-cream">
                      Translation Content
                    </h2>

                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                      {/* Original text (read-only) */}
                      {originalWork && (
                        <div className="border border-sage/20 dark:border-sage/10 rounded-lg p-4">
                          <h3 className="font-medium mb-2">Original Text ({originalWork.language})</h3>
                          <div className="max-h-[400px] overflow-y-auto p-2">
                            <pre className="whitespace-pre-wrap font-serif text-sm">{originalWork.content}</pre>
                          </div>
                        </div>
                      )}

                      {/* Translation input */}
                      <FormField
                        control={form.control}
                        name="content"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Your Translation</FormLabel>
                            <FormControl>
                              <Textarea
                                placeholder="Enter your translation here"
                                className="min-h-[400px] font-serif"
                                {...field}
                              />
                            </FormControl>
                            <FormDescription>
                              Paste or type your translation, preserving line breaks where appropriate
                            </FormDescription>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>

                    <FormField
                      control={form.control}
                      name="notes"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Translation Notes (Optional)</FormLabel>
                          <FormControl>
                            <Textarea
                              placeholder="Add any notes about your translation approach, challenges, or other relevant information"
                              className="min-h-[100px]"
                              {...field}
                            />
                          </FormControl>
                          <FormDescription>
                            These notes will be displayed to readers alongside your translation
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                )}

                {/* Step 4: Preview and Submit */}
                {currentStep === 4 && (
                  <div className="space-y-6">
                    <h2 className="text-lg font-serif font-semibold text-navy dark:text-cream">
                      Review and Submit
                    </h2>

                    <div className="flex justify-end mb-2">
                      <Button
                        type="button"
                        variant="outline"
                        onClick={() => setPreviewMode(!previewMode)}
                      >
                        {previewMode ? "Show Details" : "Preview Translation"}
                      </Button>
                    </div>

                    {previewMode ? (
                      <Card className="bg-cream dark:bg-dark-surface">
                        <CardHeader>
                          <CardTitle>{form.getValues().title}</CardTitle>
                          <CardDescription>
                            Translated to {form.getValues().language} ({form.getValues().year})
                          </CardDescription>
                        </CardHeader>
                        <CardContent>
                          <div className="prose dark:prose-invert max-w-none">
                            <LineNumberedText 
                              content={form.getValues().content} 
                              fontSizeClass="text-size-md" 
                            />
                            
                            {form.getValues().notes && (
                              <div className="mt-6 pt-4 border-t border-sage/20 dark:border-sage/10">
                                <h3 className="text-lg font-medium font-serif mb-2">Translation Notes</h3>
                                <p className="whitespace-pre-line text-sm">{form.getValues().notes}</p>
                              </div>
                            )}
                          </div>
                        </CardContent>
                      </Card>
                    ) : (
                      <div className="space-y-6">
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                          <div>
                            <h3 className="font-medium mb-2">Original Work</h3>
                            <p className="text-navy/80 dark:text-cream/80">
                              {originalWork?.title} by {originalWork?.author?.name}
                            </p>
                            <p className="text-sm text-navy/70 dark:text-cream/70">
                              {originalWork?.language}, {originalWork?.year || 'Unknown year'}
                            </p>
                          </div>
                          
                          <div>
                            <h3 className="font-medium mb-2">Translation</h3>
                            <p className="text-navy/80 dark:text-cream/80">{form.getValues().title}</p>
                            <p className="text-sm text-navy/70 dark:text-cream/70">
                              {form.getValues().language}, {form.getValues().year}
                            </p>
                          </div>
                        </div>
                        
                        <div>
                          <h3 className="font-medium mb-2">Content</h3>
                          <p className="text-sm text-navy/70 dark:text-cream/70">
                            Translation length: {form.getValues().content.split('\n').length} lines, 
                            {' '}{form.getValues().content.length} characters
                          </p>
                          <div className="mt-2 p-2 border border-sage/20 dark:border-sage/10 rounded bg-paper dark:bg-dark-paper max-h-40 overflow-y-auto">
                            <p className="text-sm whitespace-pre-line">
                              {form.getValues().content.substring(0, 300)}
                              {form.getValues().content.length > 300 ? "..." : ""}
                            </p>
                          </div>
                        </div>
                        
                        {form.getValues().notes && (
                          <div>
                            <h3 className="font-medium mb-2">Notes</h3>
                            <div className="p-2 border border-sage/20 dark:border-sage/10 rounded bg-paper dark:bg-dark-paper">
                              <p className="text-sm whitespace-pre-line">
                                {form.getValues().notes.substring(0, 200)}
                                {form.getValues().notes.length > 200 ? "..." : ""}
                              </p>
                            </div>
                          </div>
                        )}
                      </div>
                    )}

                    <div className="space-y-4 mt-6 pt-6 border-t border-sage/20 dark:border-sage/10">
                      <FormField
                        control={form.control}
                        name="acknowledgment"
                        render={({ field }) => (
                          <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                            <FormControl>
                              <Checkbox
                                checked={field.value}
                                onCheckedChange={field.onChange}
                              />
                            </FormControl>
                            <div className="space-y-1 leading-none">
                              <FormLabel>
                                I acknowledge that I have the rights to submit this translation
                              </FormLabel>
                              <FormDescription>
                                You confirm that this translation is your own work or you have permission to submit it
                              </FormDescription>
                            </div>
                          </FormItem>
                        )}
                      />
                      
                      <FormField
                        control={form.control}
                        name="terms"
                        render={({ field }) => (
                          <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                            <FormControl>
                              <Checkbox
                                checked={field.value}
                                onCheckedChange={field.onChange}
                              />
                            </FormControl>
                            <div className="space-y-1 leading-none">
                              <FormLabel>
                                I agree to the terms and conditions
                              </FormLabel>
                              <FormDescription>
                                By submitting this translation, you agree to our <a href="/terms" className="text-russet hover:underline">terms and conditions</a>
                              </FormDescription>
                            </div>
                          </FormItem>
                        )}
                      />
                    </div>
                  </div>
                )}

                {/* Navigation buttons */}
                <div className="flex justify-between pt-4">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleBack}
                    disabled={currentStep === 1 || mutation.isPending}
                  >
                    Back
                  </Button>
                  
                  <Button 
                    type="submit"
                    disabled={mutation.isPending}
                  >
                    {mutation.isPending ? (
                      <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Submitting...
                      </>
                    ) : currentStep < 4 ? (
                      "Continue"
                    ) : (
                      <>
                        <Check className="mr-2 h-4 w-4" />
                        Submit Translation
                      </>
                    )}
                  </Button>
                </div>
              </form>
            </Form>
          </div>
        )}

        {/* Coming soon message for original submissions */}
        {submissionType === 'original' && (
          <Card className="bg-cream dark:bg-dark-surface">
            <CardContent className="flex flex-col items-center justify-center text-center py-16">
              <div className="w-16 h-16 bg-navy/10 dark:bg-navy/20 rounded-full flex items-center justify-center mb-4">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-8 w-8 text-navy dark:text-cream" viewBox="0 0 24 24">
                  <path fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8V8.5M12 12v4M3.08 5.65A10 10 0 0 1 12 2c5.5 0 10 4.5 10 10s-4.5 10-10 10S2 17.5 2 12c0-1.23.22-2.4.62-3.5" />
                </svg>
              </div>
              <h2 className="text-xl font-serif font-semibold mb-2">Coming Soon</h2>
              <p className="text-navy/70 dark:text-cream/70 max-w-md mx-auto mb-6">
                The ability to submit original works is currently under development. 
                Please check back soon or contact us if you have an original work to contribute.
              </p>
              <Button variant="outline" asChild>
                <a href="mailto:contact@tercul.com">Contact Us</a>
              </Button>
            </CardContent>
          </Card>
        )}
      </div>
    </PageLayout>
  );
}
