"use client"

import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { useRouter, useParams } from "next/navigation"
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardDescription, CardTitle, CardHeader, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { IconCircleCheckFilled, IconLoader, IconCircleMinus } from "@tabler/icons-react"
import { BuildingIcon, DollarIcon } from "@/components/ui/icons"
import { useTranslation } from "react-i18next"
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/components/ui/tabs"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { Calendar } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { format } from "date-fns"
import { CalendarIcon } from "lucide-react"
import { cn } from "@/lib/utils"

interface DeliveryOrder {
  orderId: string;
  contractNumber: string;
  status: string;
  personInCharge: string;
  deliveryPeriod: {
    Delivery_date_from: string;
    Delivery_date_to: string;
    Delivery_period_Option_Code: string;
    Delivery_period_Option_RO: string;
    Delivery_period_Option_ENG: string;
  };
}

export default function PeriodOptionDetailsPage() {
  const params = useParams()
  const router = useRouter()
  const { t } = useTranslation()
  const [order, setOrder] = useState<DeliveryOrder | null>(null)
  const [loading, setLoading] = useState(true)
  const [fromDate, setFromDate] = useState<Date | undefined>(undefined)
  const [toDate, setToDate] = useState<Date | undefined>(undefined)

  useEffect(() => {
    if (params.id) {
      fetch(`/delivery-conditions/api/delivery`)
        .then(res => res.json())
        .then(data => {
          const foundOrder = data.find((order: DeliveryOrder) => order.orderId === params.id)
          if (foundOrder) {
            setOrder(foundOrder)
            // Parse dates from string format (DD/MM/YYYY)
            const [fromDay, fromMonth, fromYear] = foundOrder.deliveryPeriod.Delivery_date_from.split('/')
            const [toDay, toMonth, toYear] = foundOrder.deliveryPeriod.Delivery_date_to.split('/')
            setFromDate(new Date(parseInt(fromYear), parseInt(fromMonth) - 1, parseInt(fromDay)))
            setToDate(new Date(parseInt(toYear), parseInt(toMonth) - 1, parseInt(toDay)))
          }
          setLoading(false)
        })
        .catch(error => {
          console.error("Error fetching delivery order:", error)
          setLoading(false)
        })
    }
  }, [params.id])

  const handleBack = () => {
    if (window.history.length > 1) {
      router.back()
    } else {
      router.push("/delivery-conditions/period-option")
    }
  }

  const handleSave = async () => {
    if (!order || !fromDate || !toDate) return

    const updatedOrder = {
      ...order,
      deliveryPeriod: {
        ...order.deliveryPeriod,
        Delivery_date_from: format(fromDate, 'dd/MM/yyyy'),
        Delivery_date_to: format(toDate, 'dd/MM/yyyy')
      }
    }

    try {
      const response = await fetch('/delivery-conditions/api/delivery', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updatedOrder)
      });
      if (!response.ok) throw new Error('Failed to save changes');
      alert('Order saved!');
      router.refresh();
    } catch (error) {
      alert('Failed to save changes.');
    }
  };

  const getStatusBadge = (status: string) => (
    <Badge variant="outline" className="text-muted-foreground px-1.5">
      {status.toLowerCase() === "completed" ? (
        <IconCircleCheckFilled className="fill-green-500 dark:fill-green-400 mr-2" />
      ) : status.toLowerCase() === "pending" ? (
        <IconLoader className="mr-2" />
      ) : (
        <IconCircleMinus className="fill-gray-950 dark:fill-gray-950 mr-2" />
      )}
      {status}
    </Badge>
  )

  if (loading) return <div className="p-8">Loading...</div>
  if (!order) return <div className="p-8">Order not found.</div>

  return (
    <SidebarProvider style={{
      "--sidebar-width": "calc(var(--spacing) * 72)",
      "--header-height": "calc(var(--spacing) * 12)",
    } as React.CSSProperties}>
      <AppSidebar variant="inset" />
      <SidebarInset>
        <SiteHeader title="Period Option Details" />
        <div className="flex flex-1 flex-col">
          <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-4">
            <div className="flex justify-between items-center px-4 lg:px-6">
              <div className="flex items-center gap-4">
                <h2 className="text-2xl font-bold">Period Option {order.orderId}</h2>
                {getStatusBadge(order.status)}
              </div>
              <div className="flex gap-2">
                <Button variant="outline" onClick={handleBack}>Back</Button>
              </div>
            </div>
            <Tabs defaultValue="general" className="w-full">
              <TabsList className="px-4 lg:px-6 lg:w-full lg:h-14">
                <TabsTrigger value="general" className="flex items-center gap-2 lg:text-lg">
                  <BuildingIcon className="h-4 w-4" />
                  General
                </TabsTrigger>
                <TabsTrigger value="period" className="flex items-center gap-2 lg:text-lg">
                  <DollarIcon className="h-4 w-4" />
                  Period Details
                </TabsTrigger>
              </TabsList>

              <TabsContent value="general" className="px-4 lg:px-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <BuildingIcon className="h-5 w-5" />
                      General Information
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">Contract Number</span>
                        <Input value={order.contractNumber} onChange={e => setOrder({ ...order, contractNumber: e.target.value })} />
                      </div>
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">Order ID</span>
                        <Input value={order.orderId} readOnly />
                      </div>
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">Status</span>
                        <Input value={order.status} onChange={e => setOrder({ ...order, status: e.target.value })} />
                      </div>
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">Person in Charge</span>
                        <Input value={order.personInCharge} onChange={e => setOrder({ ...order, personInCharge: e.target.value })} />
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="period" className="px-4 lg:px-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <DollarIcon className="h-5 w-5" />
                      Period Details
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">From Date</span>
                        <Popover>
                          <PopoverTrigger asChild>
                            <Button
                              variant={"outline"}
                              className={cn(
                                "w-full justify-start text-left font-normal",
                                !fromDate && "text-muted-foreground"
                              )}
                            >
                              <CalendarIcon className="mr-2 h-4 w-4" />
                              {fromDate ? format(fromDate, "PPP") : <span>Pick a date</span>}
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent className="w-auto p-0">
                            <Calendar
                              mode="single"
                              selected={fromDate}
                              onSelect={setFromDate}
                              initialFocus
                            />
                          </PopoverContent>
                        </Popover>
                      </div>
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">To Date</span>
                        <Popover>
                          <PopoverTrigger asChild>
                            <Button
                              variant={"outline"}
                              className={cn(
                                "w-full justify-start text-left font-normal",
                                !toDate && "text-muted-foreground"
                              )}
                            >
                              <CalendarIcon className="mr-2 h-4 w-4" />
                              {toDate ? format(toDate, "PPP") : <span>Pick a date</span>}
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent className="w-auto p-0">
                            <Calendar
                              mode="single"
                              selected={toDate}
                              onSelect={setToDate}
                              initialFocus
                            />
                          </PopoverContent>
                        </Popover>
                      </div>
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">Option Code</span>
                        <Select 
                          value={order.deliveryPeriod.Delivery_period_Option_Code} 
                          onValueChange={(value) => setOrder({
                            ...order,
                            deliveryPeriod: { ...order.deliveryPeriod, Delivery_period_Option_Code: value }
                          })}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="S">S</SelectItem>
                            <SelectItem value="B">B</SelectItem>
                            <SelectItem value="S/B">S/B</SelectItem>
                            <SelectItem value="B/S">B/S</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">Option RO</span>
                        <Input 
                          value={order.deliveryPeriod.Delivery_period_Option_RO} 
                          onChange={e => setOrder({
                            ...order,
                            deliveryPeriod: { ...order.deliveryPeriod, Delivery_period_Option_RO: e.target.value }
                          })} 
                        />
                      </div>
                      <div className="flex flex-col gap-2">
                        <span className="font-medium">Option ENG</span>
                        <Input 
                          value={order.deliveryPeriod.Delivery_period_Option_ENG} 
                          onChange={e => setOrder({
                            ...order,
                            deliveryPeriod: { ...order.deliveryPeriod, Delivery_period_Option_ENG: e.target.value }
                          })} 
                        />
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </div>
          <div className="flex justify-end px-4 lg:px-6 pb-2">
            <Button onClick={handleSave}>Save Changes</Button>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
} 