"use client"

import type React from "react"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { Search, Ship, Package, MapPin, Clock, Printer, Download } from "lucide-react"

interface TrackingData {
  shipmentId: string
  status: string
  currentLocation: string
  progress: number
  events: Array<{
    status: string
    location: string
    date: string
    time: string
    description: string
    completed: boolean
  }>
  shipmentInfo: {
    bookingRef: string
    billOfLading: string
    shipper: string
    consignee: string
    origin: string
    destination: string
    cargoType: string
    weight: string
    volume: string
  }
  vesselInfo: {
    name: string
    imo: string
    voyage: string
    flag: string
    eta: string
    etd: string
  }
  containers: Array<{
    number: string
    type: string
    size: string
    sealNumber: string
    weight: string
  }>
}

const mockTrackingData: TrackingData = {
  shipmentId: "SHP-2023-001",
  status: "In Transit",
  currentLocation: "Singapore",
  progress: 65,
  events: [
    {
      status: "Booking Confirmed",
      location: "Shanghai, China",
      date: "2023-12-01",
      time: "09:00",
      description: "Booking confirmed and cargo space allocated",
      completed: true,
    },
    {
      status: "Cargo Received",
      location: "Shanghai Port",
      date: "2023-12-03",
      time: "14:30",
      description: "Cargo received at port and ready for loading",
      completed: true,
    },
    {
      status: "Loaded on Vessel",
      location: "Shanghai Port",
      date: "2023-12-05",
      time: "08:15",
      description: "Container loaded on vessel MSC OSCAR",
      completed: true,
    },
    {
      status: "Departed",
      location: "Shanghai Port",
      date: "2023-12-05",
      time: "18:00",
      description: "Vessel departed from Shanghai",
      completed: true,
    },
    {
      status: "In Transit",
      location: "Singapore",
      date: "2023-12-10",
      time: "12:00",
      description: "Vessel arrived at Singapore for transshipment",
      completed: true,
    },
    {
      status: "Arrived",
      location: "Rotterdam, Netherlands",
      date: "2023-12-20",
      time: "06:00",
      description: "Expected arrival at destination port",
      completed: false,
    },
    {
      status: "Discharged",
      location: "Rotterdam Port",
      date: "2023-12-21",
      time: "10:00",
      description: "Container to be discharged from vessel",
      completed: false,
    },
    {
      status: "Delivered",
      location: "Final Destination",
      date: "2023-12-23",
      time: "15:00",
      description: "Cargo delivered to consignee",
      completed: false,
    },
  ],
  shipmentInfo: {
    bookingRef: "BKG123456789",
    billOfLading: "BL987654321",
    shipper: "Shanghai Export Co., Ltd.",
    consignee: "Rotterdam Import B.V.",
    origin: "Shanghai, China",
    destination: "Rotterdam, Netherlands",
    cargoType: "Electronics",
    weight: "15,000 kg",
    volume: "45 m³",
  },
  vesselInfo: {
    name: "MSC OSCAR",
    imo: "9395044",
    voyage: "001E",
    flag: "Panama",
    eta: "2023-12-20 06:00",
    etd: "2023-12-05 18:00",
  },
  containers: [
    {
      number: "MSCU1234567",
      type: "Dry Container",
      size: "40ft HC",
      sealNumber: "SEAL123456",
      weight: "25,000 kg",
    },
  ],
}

export default function TrackShipmentPage() {
  const [searchType, setSearchType] = useState("shipment")
  const [searchValue, setSearchValue] = useState("")
  const [trackingData, setTrackingData] = useState<TrackingData | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")

  const handleSearch = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!searchValue.trim()) return

    setIsLoading(true)
    setError("")

    // Simulate API call
    setTimeout(() => {
      if (searchValue === "SHP-2023-001" || searchValue === "MSCU1234567") {
        setTrackingData(mockTrackingData)
      } else {
        setError("Shipment not found. Please check your tracking number and try again.")
        setTrackingData(null)
      }
      setIsLoading(false)
    }, 1500)
  }

  const handlePrint = () => {
    window.print()
  }

  const handleExport = () => {
    if (trackingData) {
      const dataStr = JSON.stringify(trackingData, null, 2)
      const dataBlob = new Blob([dataStr], { type: "application/json" })
      const url = URL.createObjectURL(dataBlob)
      const link = document.createElement("a")
      link.href = url
      link.download = `tracking-${trackingData.shipmentId}.json`
      link.click()
    }
  }

  return (
    <div className="container mx-auto py-6">
      <div className="mb-6">
        <h1 className="text-3xl font-bold">Track Shipment</h1>
        <p className="text-muted-foreground">Enter your tracking information to get real-time updates</p>
      </div>

      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Search className="h-5 w-5" />
            Search Shipment
          </CardTitle>
          <CardDescription>Enter your shipment ID, container number, or booking reference</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSearch} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="searchType">Search Type</Label>
                <Select value={searchType} onValueChange={setSearchType}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="shipment">Shipment ID</SelectItem>
                    <SelectItem value="container">Container Number</SelectItem>
                    <SelectItem value="booking">Booking Reference</SelectItem>
                    <SelectItem value="bill">Bill of Lading</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="searchValue">
                  {searchType === "shipment" && "Shipment ID"}
                  {searchType === "container" && "Container Number"}
                  {searchType === "booking" && "Booking Reference"}
                  {searchType === "bill" && "Bill of Lading"}
                </Label>
                <Input
                  id="searchValue"
                  value={searchValue}
                  onChange={(e) => setSearchValue(e.target.value)}
                  placeholder={
                    searchType === "shipment"
                      ? "SHP-2023-001"
                      : searchType === "container"
                        ? "MSCU1234567"
                        : searchType === "booking"
                          ? "BKG123456789"
                          : "BL987654321"
                  }
                  required
                />
              </div>
              <div className="flex items-end">
                <Button type="submit" disabled={isLoading} className="w-full">
                  {isLoading ? "Searching..." : "Track Shipment"}
                </Button>
              </div>
            </div>
          </form>

          {error && (
            <div className="mt-4 p-4 bg-destructive/10 border border-destructive/20 rounded-lg">
              <p className="text-destructive text-sm">{error}</p>
            </div>
          )}

          <div className="mt-4 text-sm text-muted-foreground">
            <p className="font-medium mb-2">Sample tracking numbers for testing:</p>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
              <p>• Shipment ID: SHP-2023-001</p>
              <p>• Container: MSCU1234567</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {trackingData && (
        <div className="space-y-6">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="flex items-center gap-2">
                    <Package className="h-5 w-5" />
                    Shipment {trackingData.shipmentId}
                  </CardTitle>
                  <CardDescription>Current Status: {trackingData.status}</CardDescription>
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" size="sm" onClick={handlePrint}>
                    <Printer className="h-4 w-4 mr-2" />
                    Print
                  </Button>
                  <Button variant="outline" size="sm" onClick={handleExport}>
                    <Download className="h-4 w-4 mr-2" />
                    Export
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-2">
                  <MapPin className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm">Current Location: {trackingData.currentLocation}</span>
                </div>
                <Badge variant={trackingData.status === "Delivered" ? "default" : "secondary"}>
                  {trackingData.status}
                </Badge>
              </div>

              <div className="w-full bg-secondary rounded-full h-2 mb-4">
                <div
                  className="bg-primary h-2 rounded-full transition-all duration-300"
                  style={{ width: `${trackingData.progress}%` }}
                />
              </div>

              <div className="flex justify-between text-sm text-muted-foreground">
                <span>{trackingData.shipmentInfo.origin}</span>
                <span>{trackingData.progress}% Complete</span>
                <span>{trackingData.shipmentInfo.destination}</span>
              </div>
            </CardContent>
          </Card>

          <Tabs defaultValue="tracking" className="space-y-6">
            <TabsList className="grid w-full grid-cols-4">
              <TabsTrigger value="tracking">Tracking</TabsTrigger>
              <TabsTrigger value="cargo">Cargo Info</TabsTrigger>
              <TabsTrigger value="containers">Containers</TabsTrigger>
              <TabsTrigger value="vessel">Vessel Info</TabsTrigger>
            </TabsList>

            <TabsContent value="tracking" className="space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Clock className="h-5 w-5" />
                    Tracking Timeline
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {trackingData.events.map((event, index) => (
                      <div key={index} className="flex items-start gap-4">
                        <div className={`w-3 h-3 rounded-full mt-2 ${event.completed ? "bg-primary" : "bg-muted"}`} />
                        <div className="flex-1 space-y-1">
                          <div className="flex items-center justify-between">
                            <h4
                              className={`font-medium ${event.completed ? "text-foreground" : "text-muted-foreground"}`}
                            >
                              {event.status}
                            </h4>
                            <span className="text-sm text-muted-foreground">
                              {event.date} {event.time}
                            </span>
                          </div>
                          <p className="text-sm text-muted-foreground">{event.location}</p>
                          <p className="text-sm">{event.description}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="cargo" className="space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle>Shipment Information</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <Label className="text-sm font-medium">Booking Reference</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.shipmentInfo.bookingRef}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">Bill of Lading</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.shipmentInfo.billOfLading}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">Shipper</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.shipmentInfo.shipper}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">Consignee</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.shipmentInfo.consignee}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">Origin</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.shipmentInfo.origin}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">Destination</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.shipmentInfo.destination}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">Cargo Type</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.shipmentInfo.cargoType}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">Weight</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.shipmentInfo.weight}</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="containers" className="space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle>Container Details</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {trackingData.containers.map((container, index) => (
                      <div key={index} className="border rounded-lg p-4">
                        <h4 className="font-medium mb-3">Container {index + 1}</h4>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div>
                            <Label className="text-sm font-medium">Container Number</Label>
                            <p className="text-sm text-muted-foreground">{container.number}</p>
                          </div>
                          <div>
                            <Label className="text-sm font-medium">Type & Size</Label>
                            <p className="text-sm text-muted-foreground">
                              {container.type} - {container.size}
                            </p>
                          </div>
                          <div>
                            <Label className="text-sm font-medium">Seal Number</Label>
                            <p className="text-sm text-muted-foreground">{container.sealNumber}</p>
                          </div>
                          <div>
                            <Label className="text-sm font-medium">Weight</Label>
                            <p className="text-sm text-muted-foreground">{container.weight}</p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="vessel" className="space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Ship className="h-5 w-5" />
                    Vessel Information
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <Label className="text-sm font-medium">Vessel Name</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.vesselInfo.name}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">IMO Number</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.vesselInfo.imo}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">Voyage Number</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.vesselInfo.voyage}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">Flag</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.vesselInfo.flag}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">ETD</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.vesselInfo.etd}</p>
                    </div>
                    <div>
                      <Label className="text-sm font-medium">ETA</Label>
                      <p className="text-sm text-muted-foreground">{trackingData.vesselInfo.eta}</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>
      )}
    </div>
  )
}
