'use client'

import { useState } from 'react'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Button,
  Badge,
  CameraCapture,
  PhotoGallery,
  ShareButton,
  SyncQueueBadge,
  SyncQueueStatus,
  useBackgroundSync,
  useWakeLock,
  useWebShare,
  type CapturedPhoto,
  type Photo,
} from '@kodeme-io/next-core-ui'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@kodeme-io/next-core-ui'
import { Camera, Cloud, Share2, Moon } from 'lucide-react'

export default function FieldToolsPage() {
  const [showCamera, setShowCamera] = useState(false)
  const [photos, setPhotos] = useState<Photo[]>([])
  const { add, status } = useBackgroundSync()
  const { isActive: wakeLockActive, toggle: toggleWakeLock } = useWakeLock()
  const { isSupported: shareSupported } = useWebShare()

  const handleCapture = (capturedPhoto: CapturedPhoto) => {
    const newPhoto: Photo = {
      id: `photo-${Date.now()}`,
      url: capturedPhoto.dataUrl,
      name: `visit-${Date.now()}.jpg`,
      timestamp: capturedPhoto.timestamp,
      size: capturedPhoto.size,
    }
    setPhotos([...photos, newPhoto])
    setShowCamera(false)
  }

  const handleDeletePhoto = (photoId: string) => {
    setPhotos(photos.filter((p) => p.id !== photoId))
  }

  const handleSubmitVisit = async () => {
    // Simulate API call - queue it for offline sync
    await add({
      tag: 'visit-submit',
      request: {
        url: '/api/visits',
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: {
          customerId: 'demo-customer-123',
          photos: photos.map((p) => p.url),
          notes: 'Customer visit with ' + photos.length + ' photos',
          timestamp: Date.now(),
        },
      },
      maxRetries: 5,
      priority: 1,
    })

    alert('Visit queued for sync! Try going offline and back online to see auto-sync.')
  }

  return (
    <div className="container py-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">PWA Field Tools Demo</h1>
          <p className="text-muted-foreground">
            Essential tools for field workers (Phase 1)
          </p>
        </div>
        <SyncQueueBadge alwaysShow />
      </div>

      {/* Overview Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Media Capture</CardTitle>
            <Camera className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{photos.length}</div>
            <p className="text-xs text-muted-foreground">Photos captured</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Background Sync</CardTitle>
            <Cloud className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{status.total}</div>
            <p className="text-xs text-muted-foreground">Items queued</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Web Share</CardTitle>
            <Share2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{shareSupported ? 'Yes' : 'No'}</div>
            <p className="text-xs text-muted-foreground">Supported</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Wake Lock</CardTitle>
            <Moon className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{wakeLockActive ? 'On' : 'Off'}</div>
            <p className="text-xs text-muted-foreground">Screen lock</p>
          </CardContent>
        </Card>
      </div>

      {/* Feature Demos */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Camera Capture */}
        <Card>
          <CardHeader>
            <CardTitle>📸 Media Capture</CardTitle>
            <CardDescription>
              Native camera access with photo compression and gallery
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {showCamera ? (
              <div className="h-[400px] rounded-lg overflow-hidden">
                <CameraCapture
                  onCapture={handleCapture}
                  onClose={() => setShowCamera(false)}
                  quality={0.8}
                  format="image/jpeg"
                />
              </div>
            ) : (
              <>
                <Button onClick={() => setShowCamera(true)} className="w-full">
                  <Camera className="mr-2 h-4 w-4" />
                  Open Camera
                </Button>

                {photos.length > 0 && (
                  <div>
                    <h4 className="text-sm font-medium mb-2">
                      Captured Photos ({photos.length})
                    </h4>
                    <PhotoGallery
                      photos={photos}
                      onDelete={handleDeletePhoto}
                      columns={3}
                    />
                  </div>
                )}
              </>
            )}
          </CardContent>
        </Card>

        {/* Background Sync */}
        <Card>
          <CardHeader>
            <CardTitle>🔄 Background Sync</CardTitle>
            <CardDescription>
              Offline queue with automatic retry and zero data loss
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Button
                onClick={handleSubmitVisit}
                disabled={photos.length === 0}
                className="w-full"
              >
                Submit Visit ({photos.length} photos)
              </Button>
              <p className="text-xs text-muted-foreground">
                Try going offline (airplane mode) and submitting - it will queue
                automatically!
              </p>
            </div>

            <Dialog>
              <DialogTrigger asChild>
                <Button variant="outline" className="w-full">
                  View Sync Queue
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl">
                <DialogHeader>
                  <DialogTitle>Sync Queue Status</DialogTitle>
                </DialogHeader>
                <SyncQueueStatus maxHeight="400px" showActions={true} />
              </DialogContent>
            </Dialog>
          </CardContent>
        </Card>

        {/* Web Share */}
        <Card>
          <CardHeader>
            <CardTitle>📤 Web Share</CardTitle>
            <CardDescription>
              Native sharing with automatic clipboard fallback
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <ShareButton
              data={{
                title: 'Customer Visit Report',
                text: `Visit completed with ${photos.length} photos. Check it out!`,
                url: window.location.href,
              }}
              className="w-full"
            />
            <p className="text-xs text-muted-foreground">
              {shareSupported
                ? 'Native share dialog available on this device'
                : 'Will copy to clipboard (desktop fallback)'}
            </p>
          </CardContent>
        </Card>

        {/* Wake Lock */}
        <Card>
          <CardHeader>
            <CardTitle>⏰ Wake Lock</CardTitle>
            <CardDescription>
              Prevent screen sleep during important workflows
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <Button onClick={toggleWakeLock} className="w-full" variant="outline">
              {wakeLockActive ? 'Release Wake Lock' : 'Request Wake Lock'}
            </Button>
            <div className="rounded-lg border p-3">
              <div className="flex items-center gap-2 mb-2">
                <Badge variant={wakeLockActive ? 'default' : 'secondary'}>
                  {wakeLockActive ? '🔓 Active' : '🔒 Inactive'}
                </Badge>
              </div>
              <p className="text-xs text-muted-foreground">
                {wakeLockActive
                  ? 'Screen will stay on. Great for delivery routes or long forms!'
                  : 'Screen can sleep normally. Battery friendly!'}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Features List */}
      <Card>
        <CardHeader>
          <CardTitle>📋 What You Can Do</CardTitle>
          <CardDescription>
            Real-world use cases for PWA Field Tools
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <h4 className="font-medium mb-2">📸 Media Capture</h4>
              <ul className="text-sm text-muted-foreground space-y-1">
                <li>• Take customer visit photos</li>
                <li>• Capture delivery proof-of-delivery</li>
                <li>• Document product conditions</li>
                <li>• Auto-compress to 400KB</li>
                <li>• Switch front/back camera</li>
              </ul>
            </div>
            <div>
              <h4 className="font-medium mb-2">🔄 Background Sync</h4>
              <ul className="text-sm text-muted-foreground space-y-1">
                <li>• Submit forms offline</li>
                <li>• Auto-retry when online</li>
                <li>• Zero data loss guaranteed</li>
                <li>• Track sync progress</li>
                <li>• Retry failed items</li>
              </ul>
            </div>
            <div>
              <h4 className="font-medium mb-2">📤 Web Share</h4>
              <ul className="text-sm text-muted-foreground space-y-1">
                <li>• Share via WhatsApp, SMS, Email</li>
                <li>• Send locations to team</li>
                <li>• Share reports with manager</li>
                <li>• Desktop clipboard fallback</li>
                <li>• Share files and images</li>
              </ul>
            </div>
            <div>
              <h4 className="font-medium mb-2">⏰ Wake Lock</h4>
              <ul className="text-sm text-muted-foreground space-y-1">
                <li>• Keep screen on during routes</li>
                <li>• Long form data entry</li>
                <li>• Inspection workflows</li>
                <li>• Battery-aware (auto-release)</li>
                <li>• Route-specific activation</li>
              </ul>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Documentation Link */}
      <Card className="border-primary">
        <CardHeader>
          <CardTitle>📚 Learn More</CardTitle>
          <CardDescription>
            Complete documentation for PWA Field Tools
          </CardDescription>
        </CardHeader>
        <CardContent>
          <p className="text-sm mb-4">
            Check out the comprehensive guide with examples, API reference, best
            practices, and troubleshooting tips.
          </p>
          <Button asChild>
            <a
              href="https://github.com/abc-food/next-core/blob/main/docs/408-pwa-field-tools.md"
              target="_blank"
              rel="noopener noreferrer"
            >
              Read the Field Tools Guide →
            </a>
          </Button>
        </CardContent>
      </Card>
    </div>
  )
}
