
'use client';

import { useState } from 'react';
import { useForm, type SubmitHandler } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { personalizedTrailRecommendations } from '@/ai/flows/personalized-trail-recommendations';
import type { PersonalizedTrailRecommendationsOutput } from '@/ai/flows/personalized-trail-recommendations';
import { Loader2, Wand2 } from 'lucide-react';

const formSchema = z.object({
  ridingHistory: z.string().min(10, 'Please describe your riding history.'),
  skillLevel: z.enum(['beginner', 'intermediate', 'advanced']),
  bikeType: z.string().min(2, 'Please enter your bike type.'),
  desiredTrailCharacteristics: z
    .string()
    .min(10, 'Please describe what you are looking for.'),
});

type FormValues = z.infer<typeof formSchema>;

export default function RecommendationsPage() {
  const [recommendations, setRecommendations] =
    useState<PersonalizedTrailRecommendationsOutput['recommendations']>();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      ridingHistory: '',
      skillLevel: 'intermediate',
      bikeType: 'Enduro',
      desiredTrailCharacteristics: '',
    },
  });

  const onSubmit: SubmitHandler<FormValues> = async (data) => {
    setIsLoading(true);
    setError(null);
    setRecommendations(undefined);

    try {
      const result = await personalizedTrailRecommendations(data);
      if (result && result.recommendations) {
        setRecommendations(result.recommendations);
      } else {
        setError('Could not generate recommendations. Please try again.');
      }
    } catch (e) {
      console.error(e);
      setError('An unexpected error occurred. Please try again later.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="container mx-auto max-w-4xl">
      <div className="mb-8 text-center">
        <h1 className="text-3xl font-bold tracking-tight">
          AI-Powered Trail Recommendations
        </h1>
        <p className="text-muted-foreground">
          Tell us about your riding style, and we'll suggest the perfect trails
          for you.
        </p>
      </div>

      <Card>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <CardHeader>
              <CardTitle>Your Riding Profile</CardTitle>
              <CardDescription>
                The more details you provide, the better the recommendations.
              </CardDescription>
            </CardHeader>
            <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <FormField
                control={form.control}
                name="skillLevel"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Skill Level</FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      defaultValue={field.value}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="Select your skill level" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="beginner">Beginner</SelectItem>
                        <SelectItem value="intermediate">
                          Intermediate
                        </SelectItem>
                        <SelectItem value="advanced">Advanced</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="bikeType"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Bike Type</FormLabel>
                    <FormControl>
                      <Input placeholder="e.g., Trail, Downhill" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="ridingHistory"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>Riding History</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="Describe trails you've enjoyed, your typical weekend ride, etc."
                        {...field}
                      />
                    </FormControl>
                    <FormDescription>
                      What kind of terrain do you usually ride?
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="desiredTrailCharacteristics"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>What are you looking for?</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="e.g., Fast and flowy with small jumps, technical rock gardens, scenic views..."
                        {...field}
                      />
                    </FormControl>
                    <FormDescription>
                      Describe your ideal next ride.
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
            <CardFooter>
              <Button type="submit" disabled={isLoading} className="w-full md:w-auto">
                {isLoading ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : (
                  <Wand2 className="mr-2 h-4 w-4" />
                )}
                Generate Recommendations
              </Button>
            </CardFooter>
          </form>
        </Form>
      </Card>

      {error && (
        <Card className="mt-8 border-destructive">
          <CardHeader>
            <CardTitle className="text-destructive">Error</CardTitle>
            <CardDescription>{error}</CardDescription>
          </CardHeader>
        </Card>
      )}

      {recommendations && (
        <div className="mt-8">
          <h2 className="text-2xl font-bold tracking-tight text-center mb-6">
            Here are your personalized recommendations:
          </h2>
          <div className="space-y-6">
            {recommendations.map((rec) => (
              <Card key={rec.trailName}>
                <CardHeader>
                  <div className="flex justify-between items-start">
                    <div>
                      <CardTitle>{rec.trailName}</CardTitle>
                      <CardDescription>{rec.location}</CardDescription>
                    </div>
                    <Badge variant="secondary" className="capitalize">
                      {rec.difficulty}
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent className="space-y-4">
                  <p className="text-muted-foreground">{rec.description}</p>
                  <div>
                    <h4 className="font-semibold">Why it's for you:</h4>
                    <p className="text-sm text-primary/80 italic">"{rec.reasoning}"</p>
                  </div>
                  {rec.link && (
                    <Button variant="link" asChild className="p-0 h-auto">
                      <a href={rec.link} target="_blank" rel="noopener noreferrer">
                        Learn More
                      </a>
                    </Button>
                  )}
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
