"use client"

import { useState, useEffect } from "react"
import { ArrowLeft, MapPin, Navigation, Users, Share, Settings } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { Switch } from "@/components/ui/switch"
import { Slider } from "@/components/ui/slider"
import { useLocation } from "@/hooks/use-location"
import { useRouter } from "next/navigation"

interface NearbyUser {
  id: string
  firstName: string
  lastName: string
  avatar?: string
  distance: number
  lastSeen: Date
  isOnline: boolean
  location: {
    lat: number
    lng: number
    accuracy: number
  }
}

// Mock nearby users
const mockNearbyUsers: NearbyUser[] = [
  {
    id: "1",
    firstName: "Alice",
    lastName: "Johnson",
    avatar: "/diverse-woman-portrait.png",
    distance: 0.3,
    lastSeen: new Date(),
    isOnline: true,
    location: { lat: 40.7128, lng: -74.006, accuracy: 10 },
  },
  {
    id: "2",
    firstName: "Bob",
    lastName: "Smith",
    avatar: "/thoughtful-man.png",
    distance: 1.2,
    lastSeen: new Date(Date.now() - 1000 * 60 * 15),
    isOnline: false,
    location: { lat: 40.7589, lng: -73.9851, accuracy: 15 },
  },
  {
    id: "3",
    firstName: "Carol",
    lastName: "Davis",
    avatar: "/professional-woman.png",
    distance: 2.1,
    lastSeen: new Date(),
    isOnline: true,
    location: { lat: 40.7505, lng: -73.9934, accuracy: 8 },
  },
]

export default function LocationPage() {
  const router = useRouter()
  const { location, error, loading, requestLocation, calculateDistance } = useLocation()
  const [locationSettings, setLocationSettings] = useState({
    shareLocation: true,
    showOnMap: true,
    searchRadius: 5, // km
    allowNearbySearch: true,
  })
  const [nearbyUsers, setNearbyUsers] = useState<NearbyUser[]>([])

  useEffect(() => {
    if (location && locationSettings.allowNearbySearch) {
      // Filter users within search radius
      const filtered = mockNearbyUsers.filter((user) => {
        const distance = calculateDistance(location.latitude, location.longitude, user.location.lat, user.location.lng)
        return distance <= locationSettings.searchRadius
      })
      setNearbyUsers(filtered)
    }
  }, [location, locationSettings.searchRadius, locationSettings.allowNearbySearch, calculateDistance])

  const handleLocationRequest = () => {
    requestLocation()
  }

  const handleShareLocation = async (userId: string) => {
    if (!location) return

    console.log("[v0] Sharing location with user:", userId)
    // In a real app, send location data to the user
    const locationData = {
      latitude: location.latitude,
      longitude: location.longitude,
      accuracy: location.accuracy,
      timestamp: new Date(),
    }
    console.log("[v0] Location data to share:", locationData)
  }

  const formatDistance = (distance: number) => {
    if (distance < 1) {
      return `${Math.round(distance * 1000)}m`
    }
    return `${distance.toFixed(1)}km`
  }

  const formatLastSeen = (date: Date) => {
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))

    if (minutes < 1) return "Just now"
    if (minutes < 60) return `${minutes}m ago`
    if (hours < 24) return `${hours}h ago`
    return date.toLocaleDateString()
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <div className="sticky top-0 z-10 bg-card border-b border-border p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <Button variant="ghost" size="sm" onClick={() => router.back()}>
              <ArrowLeft className="h-4 w-4" />
            </Button>
            <h1 className="text-xl font-semibold">Location Services</h1>
          </div>
          <Button variant="outline" size="sm" onClick={() => router.push("/location/settings")}>
            <Settings className="h-4 w-4 mr-1" />
            Settings
          </Button>
        </div>
      </div>

      <div className="p-4 space-y-6">
        {/* Current Location Status */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <MapPin className="h-5 w-5" />
              <span>Your Location</span>
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {!location && !loading && (
              <div className="text-center py-6">
                <Navigation className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                <p className="text-muted-foreground mb-4">Location access not enabled</p>
                <Button onClick={handleLocationRequest}>
                  <MapPin className="h-4 w-4 mr-2" />
                  Enable Location
                </Button>
              </div>
            )}

            {loading && (
              <div className="text-center py-6">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4" />
                <p className="text-muted-foreground">Getting your location...</p>
              </div>
            )}

            {error && (
              <div className="text-center py-6">
                <p className="text-destructive mb-4">Error: {error.message}</p>
                <Button variant="outline" onClick={handleLocationRequest}>
                  Try Again
                </Button>
              </div>
            )}

            {location && (
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="font-medium">Location Enabled</p>
                    <p className="text-sm text-muted-foreground">Accuracy: ±{Math.round(location.accuracy)}m</p>
                  </div>
                  <Badge variant="secondary" className="bg-green-100 text-green-800">
                    <MapPin className="h-3 w-3 mr-1" />
                    Active
                  </Badge>
                </div>

                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground">Latitude</p>
                    <p className="font-mono">{location.latitude.toFixed(6)}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">Longitude</p>
                    <p className="font-mono">{location.longitude.toFixed(6)}</p>
                  </div>
                </div>

                <div className="flex items-center justify-between">
                  <div>
                    <p className="font-medium">Share Location</p>
                    <p className="text-sm text-muted-foreground">Allow others to find you nearby</p>
                  </div>
                  <Switch
                    checked={locationSettings.shareLocation}
                    onCheckedChange={(checked) => setLocationSettings((prev) => ({ ...prev, shareLocation: checked }))}
                  />
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Search Radius Settings */}
        {location && (
          <Card>
            <CardHeader>
              <CardTitle>Search Settings</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <p className="font-medium">Search Radius</p>
                  <span className="text-sm text-muted-foreground">{locationSettings.searchRadius}km</span>
                </div>
                <Slider
                  value={[locationSettings.searchRadius]}
                  onValueChange={(value) => setLocationSettings((prev) => ({ ...prev, searchRadius: value[0] }))}
                  max={50}
                  min={1}
                  step={1}
                  className="w-full"
                />
              </div>

              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium">Allow Nearby Search</p>
                  <p className="text-sm text-muted-foreground">Appear in other users' nearby searches</p>
                </div>
                <Switch
                  checked={locationSettings.allowNearbySearch}
                  onCheckedChange={(checked) =>
                    setLocationSettings((prev) => ({ ...prev, allowNearbySearch: checked }))
                  }
                />
              </div>
            </CardContent>
          </Card>
        )}

        {/* Nearby Users */}
        {location && locationSettings.allowNearbySearch && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Users className="h-5 w-5" />
                <span>Nearby Users</span>
                <Badge variant="secondary">{nearbyUsers.length}</Badge>
              </CardTitle>
            </CardHeader>
            <CardContent>
              {nearbyUsers.length === 0 ? (
                <div className="text-center py-6">
                  <Users className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                  <p className="text-muted-foreground">No users found nearby</p>
                  <p className="text-sm text-muted-foreground mt-2">
                    Try increasing your search radius or check back later
                  </p>
                </div>
              ) : (
                <div className="space-y-3">
                  {nearbyUsers.map((user) => (
                    <div key={user.id} className="flex items-center justify-between p-3 rounded-lg border">
                      <div className="flex items-center space-x-3">
                        <div className="relative">
                          <Avatar className="h-10 w-10">
                            <AvatarImage
                              src={user.avatar || "/placeholder.svg"}
                              alt={`${user.firstName} ${user.lastName}`}
                            />
                            <AvatarFallback>
                              {user.firstName[0]}
                              {user.lastName[0]}
                            </AvatarFallback>
                          </Avatar>
                          {user.isOnline && (
                            <div className="absolute -bottom-1 -right-1 h-3 w-3 bg-green-500 border-2 border-background rounded-full" />
                          )}
                        </div>
                        <div>
                          <p className="font-medium">
                            {user.firstName} {user.lastName}
                          </p>
                          <div className="flex items-center space-x-2 text-sm text-muted-foreground">
                            <span>{formatDistance(user.distance)} away</span>
                            <span>•</span>
                            <span>{user.isOnline ? "Online" : formatLastSeen(user.lastSeen)}</span>
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Button variant="outline" size="sm" onClick={() => handleShareLocation(user.id)}>
                          <Share className="h-4 w-4 mr-1" />
                          Share
                        </Button>
                        <Button variant="default" size="sm" onClick={() => router.push(`/chat/${user.id}`)}>
                          Message
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        )}

        {/* Map View Placeholder */}
        {location && (
          <Card>
            <CardHeader>
              <CardTitle>Map View</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="aspect-video bg-muted rounded-lg flex items-center justify-center">
                <div className="text-center">
                  <MapPin className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                  <p className="text-muted-foreground">Interactive map coming soon</p>
                  <p className="text-sm text-muted-foreground mt-2">
                    Current location: {location.latitude.toFixed(4)}, {location.longitude.toFixed(4)}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  )
}
