"use client"

import { use, useState, useEffect } from "react"
import { useTranslation } from "react-i18next"
import { useRouter } from "next/navigation"
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 { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/draft-dialog"
import { Combobox } from "@/components/combobox"

type AnnexType = 
  | "ANEXA_RO_B"
  | "ANEXA_RO_S"
  | "ANEXA_ENG_B"
  | "ANEXA_ENG_S"
  | "ANEXA_BILINGV_B"
  | "ANEXA_BILINGV_S"
  | "ANEXA_MAGIC_B"
  | "ANEXA_MAGIC_S"

interface Annex {
  id: number
  annexNumber: string
  contractNumber: string
  company: string
  status: string
  type: AnnexType
  createdDate: string
  validUntil: string
  signedBy: string
  changes: string
}

export default function AnnexDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = use(params)
  const [annex, setAnnex] = useState<Annex | null>(null)
  const [isTypeSelectorOpen, setIsTypeSelectorOpen] = useState(false)
  const { t } = useTranslation()
  const router = useRouter()
  const [companyOptions, setCompanyOptions] = useState<{ value: string; label: string }[]>([])


  useEffect(() => {
    const fetchAnnex = async () => {
      try {
        const response = await fetch(`/contracts/api/annex`)
        if (response.ok) {
          const data = await response.json()
          const found = data.find((a: Annex) => a.id.toString() === resolvedParams.id)
          if (found) {
            setAnnex(found)
          }
        }
      } catch (error) {
        console.error('Error fetching annex:', error)
      }
    }
    fetchAnnex()
  }, [resolvedParams.id])

  const handleChange = (field: keyof Annex, value: Annex[keyof Annex]) => {
    if (annex) {
      setAnnex(prev => ({
        ...prev!,
        [field]: value
      }))
    }
  }

  const handleSave = async () => {
    if (!annex) return

    try {
      const response = await fetch(`/contracts/api/annex`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(annex),
      })

      if (response.ok) {
        router.push("/contracts/annex")
      }
    } catch (error) {
      console.error('Error updating annex:', error)
    }
  }

  const AnnexType: AnnexType[]= [
    "ANEXA_RO_B",
   "ANEXA_RO_S",
   "ANEXA_ENG_B",
  "ANEXA_ENG_S",
  "ANEXA_BILINGV_B",
  "ANEXA_BILINGV_S",
   "ANEXA_MAGIC_B",
   "ANEXA_MAGIC_S"
  ]

  if (!annex) {
    return <div>Loading...</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={t("annex.details")}/>
        <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("annex.details")}</h2>
                
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" onClick={() => router.back()}>
                    {t("annex.back")}
                  </Button>
                  <Button onClick={handleSave}>
                    {t("annex.save")}
                  </Button>
                </div>
              </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">
                    {AnnexType.map((type) => (
                      <Card
                        key={type}
                        className="cursor-pointer hover:bg-accent transition-colors"
                        onClick={() => {
                          handleChange('type', type)
                          setIsTypeSelectorOpen(false)
                        }}
                      >
                        <CardHeader>
                          <CardTitle className="text-lg">{t(`drafts.types.${type}`)}</CardTitle>
                        </CardHeader>
                      </Card>
                    ))}
                  </div>
                </DialogContent>
              </Dialog>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 px-4 lg:px-6">
                <Card>
                  <CardHeader>
                    <CardTitle>{t("annex.basicinfo")}</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="space-y-2">
                      <Label>{t("annex.annexnumber")}</Label>
                      <Input
                        value={annex.annexNumber}
                        onChange={(e) => setAnnex({ ...annex, annexNumber: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>{t("annex.contractnumber")}</Label>
                      <Input
                        value={annex.contractNumber}
                        onChange={(e) => setAnnex({ ...annex, contractNumber: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>{t("annex.company")}</Label>
                      <Input
                        value={annex.company}
                        onChange={(e) => setAnnex({ ...annex, company: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>{t("annex.status")}</Label>
                      <Select
                        value={annex.status}
                        onValueChange={(value) => setAnnex({ ...annex, status: value })}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder={t("annex.selectstatus")} />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="Active">{t("drafts.statusLabels.active")}</SelectItem>
                            <SelectItem value="In Progress">{t("drafts.statusLabels.inprogress")}</SelectItem>
                            <SelectItem value="Under Review">{t("drafts.statusLabels.underreview")}</SelectItem>
                            <SelectItem value="Pending Approval">{t("drafts.statusLabels.pendingapproval")}</SelectItem>
                          </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="type">{t("annex.type")}</Label>
                        <Button
                          variant="outline"
                          className="w-full justify-start"
                          onClick={() => setIsTypeSelectorOpen(true)}
                        >
                          {t(`annex.types.${annex.type}`)}
                        </Button>
                      </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>{t("annex.dates")}</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="space-y-2">
                      <Label>{t("annex.createddate")}</Label>
                      <p>{new Date(annex.createdDate).toLocaleDateString()}</p>
                    </div>
                    <div className="space-y-2">
                      <Label>{t("annex.validuntil")}</Label>
                      <Input
                        type="date"
                        value={annex.validUntil.split('T')[0]}
                        onChange={(e) => setAnnex({ ...annex, validUntil: e.target.value })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>{t("annex.signedby")}</Label>
                      <Input
                        value={annex.signedBy}
                        onChange={(e) => setAnnex({ ...annex, signedBy: e.target.value })}
                      />
                    </div>
                  </CardContent>
                </Card>

                <Card className="md:col-span-2">
                  <CardHeader>
                    <CardTitle>{t("annex.changesinfo")}</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <Textarea
                      value={annex.changes}
                      onChange={(e) => setAnnex({ ...annex, changes: e.target.value })}
                      className="min-h-[200px]"
                    />
                  </CardContent>
                </Card>
              </div>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
}