"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 GuaranteeType = "CONVENTIE_BO_RO" | "CONVENTIE_BO_ENG" | "CONVENTIE_BO_BILINGV"

interface GuaranteeFormData {
  guaranteeNumber: string
  contractNumber: string
  company: string
  status:string
  type: GuaranteeType;
  fromLocation: string
  toLocation: string
  goods: string
  quantity: number
  unit: string
  price: number
  currency: string
  notes: string
}

export default function NewGuaranteePage() {
  const [guaranteeType, setGuaranteeType] = useState<GuaranteeType | null>(null)
  const [formData, setFormData] = useState<GuaranteeFormData>({
    guaranteeNumber: "",
    contractNumber: "",
    company: "",
    status: "",
    type: "CONVENTIE_BO_RO",
    fromLocation: "",
    toLocation: "",
    goods: "",
    quantity: 0,
    unit: "",
    price: 0,
    currency: "",
    notes: ""
  })
  const { t } = useTranslation()
  const router = useRouter()

  const [isTypeSelectorOpen, setIsTypeSelectorOpen] = useState(true)
  const [goodsOptions, setGoodsOptions] = useState<{ value: string; label: string }[]>([])
  const [companyOptions, setCompanyOptions] = useState<{ value: string; label: string }[]>([])

  useEffect(() => {
    // Fetch options for companies, goods, and payment terms
    fetch('/contracts/api/guarantees')
      .then(res => res.json())
      .then(data => {
        const goodsSet = new Set<string>(data.map((item: GuaranteeFormData) => item.goods))
        const companiesSet = new Set<string>(data.map((item: GuaranteeFormData) => item.company))

        setGoodsOptions(Array.from(goodsSet).map(item => ({ value: item, label: item })))
        setCompanyOptions(Array.from(companiesSet).map(item => ({ value: item, label: item })))
      })
  }, [])

  const handleInputChange = (field: keyof GuaranteeFormData, value: string | number) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const handleSubmit = async () => {
    try {
      const response = await fetch("/contracts/api/guarantees", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          ...formData,
          type: guaranteeType,
          status: "Pending",
          createdDate: new Date().toISOString(),
          validUntil: new Date().toISOString(),
          signedBy: "Pending"
        }),
      })

      if (response.ok) {
        router.push("/contracts/guarantee")
      }
    } catch (error) {
      console.error("Error creating guarantee:", error)
    }
  }

  const guaranteesTypes: GuaranteeType[] = [
    "CONVENTIE_BO_RO" , "CONVENTIE_BO_ENG" , "CONVENTIE_BO_BILINGV"
  ]

  const handleTypeSelect = (type: GuaranteeType) => {
    handleInputChange('type', type)
    const randomNum = Math.floor(1000 + Math.random() * 9000) // Generate a random 4-digit number
    const guaranteeNumber = `${type.slice(0, 2)}${randomNum}` // Combine first 2 letters of type with random number
    handleInputChange('guaranteeNumber', guaranteeNumber) // 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("guarantee.new")}/>
        <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("guarantee.new")}</h2>
                </div>
                <Button variant="outline" onClick={() => router.back()}>
                  {t("guarantee.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">
                    {guaranteesTypes.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("guarantee.basicinfo")}</CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="space-y-2">
                          <Label htmlFor="guaranteeNumber">{t("guarantee.guaranteenumber")}</Label>
                          <Input
                            id="guaranteeNumber"
                            value={formData.guaranteeNumber}
                            readOnly 
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="contractNumber">{t("guarantee.contractnumber")}</Label>
                          <Input
                            id="contractNumber"
                            value={formData.contractNumber}
                            onChange={(e) => handleInputChange('contractNumber', e.target.value)}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="company">{t("guarantee.company")}</Label>
                          <Combobox
                            items={companyOptions}
                            value={formData.company}
                            onValueChange={(value) => handleInputChange('company', value)}
                            placeholder="Select company"
                            emptyText="No companies found"
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="type">{t("guarantee.type")}</Label>
                          <Button
                            variant="outline"
                            className="w-full justify-start"
                            onClick={() => setIsTypeSelectorOpen(true)}
                          >
                            {t(`guarantee.types.${formData.type}`)}
                          </Button>
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle>{t("guarantee.locationinfo")}</CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="space-y-2">
                          <Label htmlFor="fromLocation">{t("guarantee.fromlocation")}</Label>
                          <Input
                            id="fromLocation"
                            value={formData.fromLocation}
                            onChange={(e) => handleInputChange('fromLocation', e.target.value)}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="toLocation">{t("guarantee.tolocation")}</Label>
                          <Input
                            id="toLocation"
                            value={formData.toLocation}
                            onChange={(e) => handleInputChange('toLocation', e.target.value)}
                          />
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle>{t("guarantee.goodsinfo")}</CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="space-y-2">
                          <Label htmlFor="goods">{t("guarantee.goods")}</Label>
                          <Input
                            id="goods"
                            value={formData.goods}
                            onChange={(e) => handleInputChange('goods', e.target.value)}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="quantity">{t("guarantee.quantity")}</Label>
                          <Input
                            id="quantity"
                            type="number"
                            value={formData.quantity}
                            onChange={(e) => handleInputChange('quantity', Number(e.target.value))}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="unit">{t("guarantee.unit")}</Label>
                          <Input
                            id="unit"
                            value={formData.unit}
                            onChange={(e) => handleInputChange('unit', e.target.value)}
                          />
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle>{t("guarantee.financialinfo")}</CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="space-y-2">
                          <Label htmlFor="price">{t("guarantee.price")}</Label>
                          <Input
                            id="price"
                            type="number"
                            value={formData.price}
                            onChange={(e) => handleInputChange('price', Number(e.target.value))}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="currency">{t("guarantee.currency")}</Label>
                          <Input
                            id="currency"
                            value={formData.currency}
                            onChange={(e) => handleInputChange('currency', e.target.value)}
                          />
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle>{t("guarantee.notes")}</CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-2">
                          <Label htmlFor="notes">{t("guarantee.notes")}</Label>
                          <Input
                            id="notes"
                            value={formData.notes}
                            onChange={(e) => handleInputChange('notes', e.target.value)}
                          />
                        </div>
                      </CardContent>
                    </Card>

                    <div className="md:col-span-2 flex justify-end">
                      <Button onClick={handleSubmit}>{t("guarantee.create")}</Button>
                    </div>
                  </div>
                
              </div>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
} 