'use client'

import { useState } from 'react'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Button,
  Badge,
  MobileHeader,
  useOnlineStatus,
  useInstallPrompt,
  getCurrentPosition,
  calculateDistance,
  formatDistance,
  formatDate,
  formatDateTime,
  getRelativeTime,
  toOdooDatetime,
} from '@kodeme-io/next-core-ui'
import { Wifi, WifiOff, Download, MapPin, Calendar, Smartphone } from 'lucide-react'

export default function ExamplesPage() {
  const isOnline = useOnlineStatus()
  const { isInstallable, isInstalled, install } = useInstallPrompt()
  const [position, setPosition] = useState<{ latitude: number; longitude: number } | null>(null)
  const [distance, setDistance] = useState<number | null>(null)

  const handleGetLocation = async () => {
    try {
      const pos = await getCurrentPosition()
      setPosition({ latitude: pos.latitude, longitude: pos.longitude })

      // Calculate distance to Jakarta (example)
      const jakartaLat = -6.2088
      const jakartaLon = 106.8456
      const dist = calculateDistance(pos.latitude, pos.longitude, jakartaLat, jakartaLon)
      setDistance(dist)
    } catch (error) {
      console.error('Failed to get location:', error)
      alert('Failed to get location. Make sure you granted permission.')
    }
  }

  const handleInstallPWA = async () => {
    const success = await install()
    if (success) {
      alert('App installed successfully!')
    }
  }

  return (
    <div className="min-h-screen bg-background">
      <MobileHeader
        title="Feature Examples"
        showBack
        backUrl="/"
      />

      <div className="container mx-auto p-4 space-y-4">
        {/* Online Status */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              {isOnline ? (
                <Wifi className="h-5 w-5 text-green-500" />
              ) : (
                <WifiOff className="h-5 w-5 text-amber-500" />
              )}
              Network Status
            </CardTitle>
            <CardDescription>Real-time online/offline detection</CardDescription>
          </CardHeader>
          <CardContent>
            <Badge variant={isOnline ? 'default' : 'secondary'}>
              {isOnline ? 'Online' : 'Offline'}
            </Badge>
            <p className="text-sm text-muted-foreground mt-2">
              {isOnline
                ? 'You are connected to the internet'
                : 'You are offline. Changes will sync when reconnected.'}
            </p>
          </CardContent>
        </Card>

        {/* PWA Installation */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Download className="h-5 w-5" />
              PWA Installation
            </CardTitle>
            <CardDescription>Install this app on your device</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {isInstalled ? (
              <Badge variant="default">App is installed</Badge>
            ) : isInstallable ? (
              <div className="space-y-2">
                <Badge variant="secondary">Installation available</Badge>
                <Button onClick={handleInstallPWA} className="w-full">
                  <Download className="h-4 w-4 mr-2" />
                  Install App
                </Button>
              </div>
            ) : (
              <Badge variant="outline">Not installable on this device</Badge>
            )}
            <p className="text-xs text-muted-foreground">
              Install this app to use it offline and get a native app experience.
            </p>
          </CardContent>
        </Card>

        {/* GPS / Geolocation */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MapPin className="h-5 w-5" />
              GPS & Geolocation
            </CardTitle>
            <CardDescription>Get your current location</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <Button onClick={handleGetLocation} variant="outline" className="w-full">
              <MapPin className="h-4 w-4 mr-2" />
              Get Location
            </Button>

            {position && (
              <div className="space-y-2 p-3 bg-muted rounded-lg">
                <div className="text-sm">
                  <strong>Latitude:</strong> {position.latitude.toFixed(6)}
                </div>
                <div className="text-sm">
                  <strong>Longitude:</strong> {position.longitude.toFixed(6)}
                </div>
                {distance !== null && (
                  <div className="text-sm">
                    <strong>Distance to Jakarta:</strong> {formatDistance(distance)}
                  </div>
                )}
              </div>
            )}

            <p className="text-xs text-muted-foreground">
              Uses browser Geolocation API for GPS positioning and distance calculations.
            </p>
          </CardContent>
        </Card>

        {/* Date Formatting */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Calendar className="h-5 w-5" />
              Date Utilities
            </CardTitle>
            <CardDescription>Format dates for display and Odoo</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="space-y-2 p-3 bg-muted rounded-lg text-sm">
              <div>
                <strong>Current Date:</strong> {formatDate(new Date())}
              </div>
              <div>
                <strong>Current DateTime:</strong> {formatDateTime(new Date())}
              </div>
              <div>
                <strong>Relative Time:</strong> {getRelativeTime(new Date())}
              </div>
              <div>
                <strong>Odoo Format:</strong> {toOdooDatetime(new Date())}
              </div>
            </div>

            <p className="text-xs text-muted-foreground">
              Utilities for date formatting, Odoo integration, and localization.
            </p>
          </CardContent>
        </Card>

        {/* Component Examples */}
        <Card>
          <CardHeader>
            <CardTitle>Available Components</CardTitle>
            <CardDescription>PWA and mobile components included</CardDescription>
          </CardHeader>
          <CardContent>
            <ul className="space-y-1 text-sm">
              <li>✅ PWAProvider - Service worker & installation</li>
              <li>✅ OfflineBanner - Network status indicator</li>
              <li>✅ AuthWrapper - Route protection</li>
              <li>✅ MobileHeader - Mobile-optimized headers</li>
              <li>✅ AppShell - Responsive layout with navigation</li>
              <li>✅ ThemeProvider - Dark/light mode support</li>
            </ul>
          </CardContent>
        </Card>

        {/* Utility Functions */}
        <Card>
          <CardHeader>
            <CardTitle>Available Utilities</CardTitle>
            <CardDescription>24 utility functions ready to use</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-sm">
              <div>
                <strong className="block mb-1">PWA Utils:</strong>
                <ul className="space-y-0.5 text-xs text-muted-foreground">
                  <li>• registerServiceWorker()</li>
                  <li>• useOnlineStatus()</li>
                  <li>• useInstallPrompt()</li>
                  <li>• isPWAInstalled()</li>
                </ul>
              </div>
              <div>
                <strong className="block mb-1">Geofence Utils:</strong>
                <ul className="space-y-0.5 text-xs text-muted-foreground">
                  <li>• calculateDistance()</li>
                  <li>• validateGeofence()</li>
                  <li>• getCurrentPosition()</li>
                  <li>• watchPosition()</li>
                </ul>
              </div>
              <div>
                <strong className="block mb-1">Date Utils:</strong>
                <ul className="space-y-0.5 text-xs text-muted-foreground">
                  <li>• toOdooDatetime()</li>
                  <li>• formatDate()</li>
                  <li>• getRelativeTime()</li>
                  <li>• addDays(), isToday()</li>
                </ul>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
