import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { useLocation } from "wouter";
import { trpc } from "@/lib/trpc";
import { toast } from "sonner";
import { CheckCircle2, ArrowLeft, Loader2 } from "lucide-react";

const applicationSchema = z.object({
  fullName: z.string().min(2, "Full name must be at least 2 characters"),
  stageName: z.string().optional(),
  category: z.string().min(1, "Please select a talent category"),
  instagramLink: z.string().url("Please enter a valid Instagram URL").optional().or(z.literal("")),
  tiktokLink: z.string().url("Please enter a valid TikTok URL").optional().or(z.literal("")),
  videoLink: z.string().url("Please enter a valid video URL").optional().or(z.literal("")),
  location: z.string().min(2, "Please enter your city"),
  yearsOfExperience: z.coerce.number().min(0, "Years must be 0 or more"),
  pastEvents: z.string().optional(),
});

type ApplicationFormData = z.infer<typeof applicationSchema>;

const TALENT_CATEGORIES = [
  "Live Bands",
  "DJs",
  "Saxophonists",
  "Church Instrumentalists",
  "MCs & Event Hosts",
  "Voice-over Artists",
  "Solo Performers",
];

export default function Apply() {
  const [, navigate] = useLocation();
  const [submitted, setSubmitted] = useState(false);
  const submitApplicationMutation = trpc.applications.submit.useMutation();

  const form = useForm<ApplicationFormData>({
    resolver: zodResolver(applicationSchema) as any,
    defaultValues: {
      fullName: "",
      stageName: "",
      category: "",
      instagramLink: "",
      tiktokLink: "",
      videoLink: "",
      location: "",
      yearsOfExperience: 0,
      pastEvents: "",
    },
  });

  const videoLinkValue = form.watch("videoLink");
  const hasVideo = videoLinkValue && videoLinkValue.trim().length > 0;

  const handleVideoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    form.setValue("videoLink", e.target.value);
  };

  const onSubmit = async (data: ApplicationFormData) => {
    try {
      await submitApplicationMutation.mutateAsync(data);
      setSubmitted(true);
      toast.success("Application submitted successfully!");
      setTimeout(() => {
        navigate("/");
      }, 3000);
    } catch (error) {
      toast.error("Failed to submit application. Please try again.");
      console.error(error);
    }
  };

  if (submitted) {
    return (
      <div className="min-h-screen bg-background text-foreground flex items-center justify-center px-4">
        <Card className="bg-card border-border max-w-md w-full p-8 text-center">
          <div className="mb-6 flex justify-center">
            <div className="w-16 h-16 rounded-full bg-accent/10 flex items-center justify-center">
              <CheckCircle2 className="h-8 w-8 text-accent" />
            </div>
          </div>
          <h2 className="text-3xl font-bold mb-4">Application Submitted!</h2>
          <p className="text-muted-foreground mb-6">
            Thank you for applying to join the Founding 50. Our team will review your profile within 3–5 days.
          </p>
          <p className="text-sm text-muted-foreground mb-8">
            We'll notify you via email once we've completed our review.
          </p>
          <Button
            onClick={() => navigate("/")}
            className="w-full bg-accent hover:bg-accent/90 text-accent-foreground font-semibold"
          >
            Back to Home
          </Button>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background text-foreground">
      <nav className="fixed top-0 w-full bg-background/80 backdrop-blur-md border-b border-border z-50">
        <div className="container flex items-center justify-between h-16">
          <Button
            variant="ghost"
            onClick={() => navigate("/")}
            className="text-muted-foreground hover:text-foreground"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back
          </Button>
          <img 
            src="https://files.manuscdn.com/user_upload_by_module/session_file/310519663273617054/OvdqELJEnlKYsShR.png" 
            alt="Vocalclips Logo" 
            className="h-14 w-auto"
          />
          <div className="w-16"></div>
        </div>
      </nav>

      <div className="pt-24 pb-12 px-4">
        <div className="container max-w-2xl mx-auto">

          <div className="mb-8">
            <h1 className="text-4xl font-bold mb-2">Apply to Join the Founding 50</h1>
            <p className="text-muted-foreground">
              Tell us about yourself and your talent. We will review your application within 3-5 days.
            </p>
          </div>

        <Card className="bg-card border-border p-8">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              {/* Full Name */}
              <FormField
                control={form.control}
                name="fullName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Full Name *</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Your full name"
                        className="bg-input border-border"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Stage Name */}
              <FormField
                control={form.control}
                name="stageName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Stage Name (Optional)</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Your stage name or artist name"
                        className="bg-input border-border"
                        value={field.value || ""}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                      />
                    </FormControl>
                    <FormDescription>
                      The name you perform under, if different from your full name
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Category */}
              <FormField
                control={form.control}
                name="category"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Talent Category *</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger className="bg-input border-border">
                          <SelectValue placeholder="Select your category" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent className="bg-card border-border">
                        {TALENT_CATEGORIES.map((cat) => (
                          <SelectItem key={cat} value={cat}>
                            {cat}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Instagram Link */}
              <FormField
                control={form.control}
                name="instagramLink"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Instagram Link (Optional)</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="https://instagram.com/yourprofile"
                        className="bg-input border-border"
                        value={field.value || ""}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* TikTok Link */}
              <FormField
                control={form.control}
                name="tiktokLink"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>TikTok Link (Optional)</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="https://tiktok.com/@yourprofile"
                        className="bg-input border-border"
                        value={field.value || ""}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Video Link */}
              <FormField
                control={form.control}
                name="videoLink"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Performance Video Link (Optional)</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="https://youtube.com/watch?v=... or similar"
                        className="bg-input border-border"
                        value={field.value || ""}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                      />
                    </FormControl>
                    <FormDescription>
                      {hasVideo ? (
                        <span className="text-accent font-semibold">✓ Video portfolio included - you have a strong advantage in our review process!</span>
                      ) : (
                        <span>Link to a video showcasing your performance. <span className="text-accent font-semibold">Artists with video portfolios have significantly better onboarding chances.</span> You can submit without one, but we highly encourage it.</span>
                      )}
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Location */}
              <FormField
                control={form.control}
                name="location"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Location (City) *</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Your city"
                        className="bg-input border-border"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Years of Experience */}
              <FormField
                control={form.control}
                name="yearsOfExperience"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Years of Experience *</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder="0"
                        className="bg-input border-border"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Past Events */}
              <FormField
                control={form.control}
                name="pastEvents"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Past Major Events (Optional)</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="List any major events, venues, or notable performances"
                        className="bg-input border-border resize-none"
                        rows={4}
                        value={field.value || ""}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                      />
                    </FormControl>
                    <FormDescription>
                      Tell us about your most impressive performances
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Submit Button */}
              <Button
                type="submit"
                disabled={submitApplicationMutation.isPending}
                className="w-full bg-accent hover:bg-accent/90 text-accent-foreground font-bold h-12"
              >
                {submitApplicationMutation.isPending ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    Submitting...
                  </>
                ) : (
                  "Submit My Application"
                )}
              </Button>

              <p className="text-xs text-muted-foreground text-center">
                By submitting, you agree to our terms and privacy policy
              </p>
            </form>
          </Form>
        </Card>
        </div>
      </div>
    </div>
  );
}
