"use client"; import { useState } from "react"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import * as z from "zod"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; // Form validation schema const shareFormSchema = z.object({ email: z.string().email("Please enter a valid email address"), senderName: z.string().min(1, "Please enter your name"), expiryHours: z.coerce.number().min(0).optional(), }); type ShareFormValues = z.infer; interface ShareLocationFormProps { location: { latitude: number; longitude: number; accuracy?: number; } | null; } export default function ShareLocationForm({ location }: ShareLocationFormProps) { const [isSubmitting, setIsSubmitting] = useState(false); const form = useForm({ resolver: zodResolver(shareFormSchema), defaultValues: { email: "", senderName: "", expiryHours: 24, }, }); const onSubmit = async (values: ShareFormValues) => { if (!location) { toast.error("No location data available to share"); return; } setIsSubmitting(true); try { const response = await fetch("/api/share-location", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ ...values, latitude: location.latitude, longitude: location.longitude, accuracy: location.accuracy, }), }); const data = await response.json(); if (!response.ok) { if (data.emailError) { toast.error(`Email error: ${data.message || 'Failed to send notification email'}`); toast.info("Location was generated but notification couldn't be sent"); return; } throw new Error(data.message || data.error || "Failed to share location"); } if (data.data?.devMode) { toast.success("Dev mode: Email would be sent (check server logs)"); form.reset(); return; } toast.success(`Location shared with ${values.email}`); form.reset(); } catch (error) { console.error("Error sharing location:", error); toast.error("Failed to share location. Please try again."); } finally { setIsSubmitting(false); } }; return ( Share Your Location
( Email Address The email address to share your location with. )} /> ( Your Name Your name will be included in the email. )} /> ( Expiry Time (hours) How long the location share will be valid (0 for no expiry) )} />
); }