"use client"

import { Button } from "@/components/ui/button"
import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import Link from "next/link"
import { useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
import { DataTableContracts } from "@/components/data-table-contracts"
import { ColumnDef } from "@tanstack/react-table"
import { Badge } from "@/components/ui/badge"
import { IconCircleCheckFilled, IconLoader,IconEye } from "@tabler/icons-react"
import { Input } from "@/components/ui/input"
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 AnnexListPage() {
  const [annexes, setAnnexes] = useState<Annex[]>([])
  const [searchQuery, setSearchQuery] = useState("")
  const { t } = useTranslation()
  const [selectedCompany, setSelectedCompany] = useState("all")

  useEffect(() => {
    fetch("/contracts/api/annex")
      .then(res => res.json())
      .then(setAnnexes)
  }, [])

  const companies = [...new Set(annexes.map(annex => annex.company))];

  const filteredAnnexes = annexes.filter(annex =>{
    const matchesSearch = 
      annex.annexNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
      annex.contractNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
      annex.company.toLowerCase().includes(searchQuery.toLowerCase());

    const matchesCompany = selectedCompany === "all" || annex.company === selectedCompany; // Check for selected company

    return matchesSearch && matchesCompany; 
  })

  const columns: ColumnDef<Annex>[] = [
    {
      accessorKey: "annexNumber",
      header: t("annex.annexnumber"),
    },
    {
      accessorKey: "contractNumber",
      header: t("annex.contractnumber"),
    },
    {
      accessorKey: "company",
      header: t("annex.company"),
    },
    {
      accessorKey: "status",
      header: t("annex.status"),
      cell: ({ row }) => (
        <Badge variant="outline" className="flex items-center gap-1">
          {row.original.status === "Active" ? (
            <>
              <IconCircleCheckFilled className="h-4 w-4 text-green-500" />
              {t("annex.active")}
            </>
          ) : (
            <>
              <IconLoader className="h-4 w-4 text-yellow-500 animate-spin" />
              {t("annex.pending")}
            </>
          )}
        </Badge>
      ),
    },
    {
      accessorKey: "type",
      header: t("annex.type"),
      cell: ({ row }) => (
        <span>{t(`annex.types.${row.original.type}`)}</span>
      ),
    },
    {
      accessorKey: "createdDate",
      header: t("annex.createddate"),
      cell: ({ row }) => (
        <span>{new Date(row.original.createdDate).toLocaleDateString()}</span>
      ),
    },
    {
      accessorKey: "validUntil",
      header: t("annex.validuntil"),
      cell: ({ row }) => (
        <span>{new Date(row.original.validUntil).toLocaleDateString()}</span>
      ),
    },
    {
      accessorKey: "signedBy",
      header: t("annex.signedby"),
    },
    {
      id: "actions",
      header: t("annex.action"),
      cell: ({ row }) => (
        <div className="flex">
          <Link href={`/contracts/annex/${row.original.id}`}>
            <Button size="sm" variant="outline"><IconEye className="h-4 w-4" />{t("drafts.view")}</Button>
          </Link>
        </div>
      ),
    },
  ]

  const companyOptions = [
    { value: "all", label: "All Companies" },
    ...companies.map(company => ({ value: company, label: company }))
  ];

  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.annexlist")}/>
        <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">
                <h2 className="text-2xl font-bold">{t("annex.annexlist")}</h2>
                <Link href="/contracts/annex/new">
                  <Button>{t("annex.newannex")}</Button>
                </Link>
              </div>
              <div className="px-4 lg:px-6">
                <div className="flex items-center gap-4 mb-4 justify-between">
                  <Input
                    placeholder={t("annex.search")}
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="max-w-sm"
                  />
                   <Combobox
                    items={companyOptions}
                    value={selectedCompany}
                    onValueChange={setSelectedCompany}
                    placeholder="Select company"
                    emptyText="No companies found"
                  />
                </div>
                <div className="rounded-md border">
                  <DataTableContracts 
                    data={filteredAnnexes} 
                    columns={columns}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
}