"use client"

import { useState,useEffect } from "react"
import { useRouter } from "next/navigation"
import { useTranslation } from "react-i18next"
import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/draft-dialog"
import { Combobox } from "@/components/combobox"

type WHRType = "WHR_RO" | "WHR_EN" | "WHR_BLINGV"

interface WHRFormData {
  contractNumber: string
  whrNumber: string
  company: string
  status: string
  type: WHRType
  warehouse: string
  goods: string
  quantity: number
  unit: string
  quality: string
  storageConditions: string
  notes: string
}

export default function NewWHRPage() {
  const [whrType, setWHRType] = useState<WHRType | null>(null)
  const [formData, setFormData] = useState<WHRFormData>({
    contractNumber: "",
    whrNumber: "",
    company: "",
    status: "",
    type: "WHR_RO",
    warehouse: "",
    goods: "",
    quantity: 0,
    unit: "",
    quality: "",
    storageConditions: "",
    notes: ""
  })
  const [isTypeSelectorOpen, setIsTypeSelectorOpen] = useState(true)
  const [goodsOptions, setGoodsOptions] = useState<{ value: string; label: string }[]>([])
  const [companyOptions, setCompanyOptions] = useState<{ value: string; label: string }[]>([])
  const { t } = useTranslation()
  const router = useRouter()

  useEffect(() => {
    // Fetch options for companies, goods, and payment terms
    fetch('/contracts/api/drafts')
      .then(res => res.json())
      .then(data => {
        const goodsSet = new Set<string>(data.map((item: WHRFormData) => item.goods))
        const companiesSet = new Set<string>(data.map((item: WHRFormData) => item.company))

        setGoodsOptions(Array.from(goodsSet).map(item => ({ value: item, label: item })))
        setCompanyOptions(Array.from(companiesSet).map(item => ({ value: item, label: item })))
      })
  }, [])

  const handleChange = (field: keyof WHRFormData, value: WHRFormData[keyof WHRFormData]) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const handleSubmit = async () => {
    try {
      const response = await fetch("/contracts/api/whrs", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          ...formData,
          type: whrType,
          status: "Pending",
          createdDate: new Date().toISOString(),
          validUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(), // 30 days from now
          signedBy: "Pending"
        }),
      })

      if (response.ok) {
        router.push("/contracts/whr")
      }
    } catch (error) {
      console.error("Error creating WHR:", error)
    }
  }

  const whrTypes: WHRType[] = [
      "WHR_RO" , "WHR_EN" , "WHR_BLINGV"
  ]

  const handleTypeSelect = (type: WHRType) => {
    handleChange('type', type)
    const randomNum = Math.floor(1000 + Math.random() * 9000) // Generate a random 4-digit number
    const whrNumber = `${type.slice(0, 2)}${randomNum}` // Combine first 2 letters of type with random number
    handleChange('whrNumber', whrNumber) // Set the draft number
    setIsTypeSelectorOpen(false) // Close the dialog
  }

  return (
    <SidebarProvider
      style={{
        "--sidebar-width": "calc(var(--spacing) * 72)",
        "--header-height": "calc(var(--spacing) * 12)",
      } as React.CSSProperties}
    >
      <AppSidebar variant="inset" />
      <SidebarInset>
        <SiteHeader title={t("whr.newwhr")} />
        <div className="flex flex-1 flex-col">
          <div className="@container/main flex flex-1 flex-col gap-2">
            <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
              <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">{t("whr.newwhr")}</h2>
                </div>
                <Button variant="outline" onClick={() => router.back()}>
                  {t("whr.back")}
                </Button>
              </div>

              <Dialog open={isTypeSelectorOpen} onOpenChange={setIsTypeSelectorOpen}>
                <DialogContent className="max-w-4xl">
                  <DialogHeader>
                    <DialogTitle>{t("drafts.selecttype")}</DialogTitle>
                  </DialogHeader>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {whrTypes.map((type) => (
                      <Card
                        key={type}
                        className="cursor-pointer hover:bg-accent transition-colors"
                        onClick={() => handleTypeSelect(type)}
                      >
                        <CardHeader>
                          <CardTitle className="text-lg">{t(`drafts.types.${type}`)}</CardTitle>
                        </CardHeader>
                      </Card>
                    ))}
                  </div>
                </DialogContent>
              </Dialog>

              <div className="px-4 lg:px-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <Card>
                      <CardHeader>
                        <CardTitle>{t("whr.basicinfo")}</CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        
                        <div className="space-y-2">
                          <Label htmlFor="whrNumber">{t("whr.whrnumber")}</Label>
                          <Input
                            id="whrNumber"
                            value={formData.whrNumber}
                            readOnly 
                            />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="contractNumber">{t("whr.contractnumber")}</Label>
                          <Input
                            id="contractNumber"
                            value={formData.contractNumber}
                            onChange={(e) => setFormData({ ...formData, contractNumber: e.target.value })}
                          />
                        </div>
                        <div className="space-y-2">
                        <Label htmlFor="company">{t("whr.company")}</Label>
                        <Combobox
                          items={companyOptions}
                          value={formData.company}
                          onValueChange={(value) => handleChange('company', value)}
                          placeholder="Select company"
                          emptyText="No companies found"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="type">{t("whr.type")}</Label>
                        <Button
                          variant="outline"
                          className="w-full justify-start"
                          onClick={() => setIsTypeSelectorOpen(true)}
                        >
                          {t(`whr.types.${formData.type}`)}
                        </Button>
                      </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle>{t("whr.warehouseinfo")}</CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="space-y-2">
                          <Label htmlFor="warehouse">{t("whr.warehouse")}</Label>
                          <Input
                            id="warehouse"
                            value={formData.warehouse}
                            onChange={(e) => setFormData({ ...formData, warehouse: e.target.value })}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="storageConditions">{t("whr.storageconditions")}</Label>
                          <Input
                            id="storageConditions"
                            value={formData.storageConditions}
                            onChange={(e) => setFormData({ ...formData, storageConditions: e.target.value })}
                          />
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle>{t("whr.goodsinfo")}</CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="space-y-2">
                          <Label htmlFor="goods">{t("whr.goods")}</Label>
                          <Input
                            id="goods"
                            value={formData.goods}
                            onChange={(e) => setFormData({ ...formData, goods: e.target.value })}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="quantity">{t("whr.quantity")}</Label>
                          <Input
                            id="quantity"
                            type="number"
                            value={formData.quantity}
                            onChange={(e) => setFormData({ ...formData, quantity: Number(e.target.value) })}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="quality">{t("whr.quality")}</Label>
                          <Input
                            id="quality"
                            value={formData.quality}
                            onChange={(e) => setFormData({ ...formData, quality: e.target.value })}
                          />
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle>{t("whr.notes")}</CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-2">
                          <Label htmlFor="notes">{t("whr.notes")}</Label>
                          <Input
                            id="notes"
                            value={formData.notes}
                            onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                          />
                        </div>
                      </CardContent>
                    </Card>

                    <div className="md:col-span-2 flex justify-end">
                      <Button onClick={handleSubmit}>{t("whr.create")}</Button>
                    </div>
                  </div>
              </div>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
} 