"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 { 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"
import Link from "next/link"

interface Guarantee {
  id: number
  guaranteeNumber: string
  contractNumber: string
  company: string
  status: string
  type: string
  createdDate: string
  validUntil: string
  fromLocation: string
  toLocation: string
  goods: string
  quantity: number
  unit: string
  price: number
  currency: string
  notes: string
  signedBy: string
}

export default function GuaranteePage() {
  
  const [guarantees, setGuarantees] = useState<Guarantee[]>([])
  const [searchQuery, setSearchQuery] = useState("")
  const { t } = useTranslation()
  const router = useRouter()
  const [selectedCompany, setSelectedCompany] = useState("all")


  useEffect(() => {
    fetch("/contracts/api/guarantees")
      .then(res => res.json())
      .then(data => {
        const mappedData = data.map((guarantee: any) => ({
          id: guarantee.id,
          contractNumber: guarantee.contractNumber,
          guaranteeNumber: guarantee.guaranteeNumber,
          company: guarantee.company,
          status: guarantee.status,
          signedBy: guarantee.signedBy
        }))
        setGuarantees(mappedData)
      })
  }, [])

  const companies = [...new Set(guarantees.map(draft => draft.company))];

  const filteredDrafts = guarantees.filter(draft => {
    const matchesSearch = 
      draft.guaranteeNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
      draft.contractNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
      draft.company.toLowerCase().includes(searchQuery.toLowerCase()) 

    const matchesCompany = selectedCompany === "all" || draft.company === selectedCompany; // Check for selected company

    return matchesSearch && matchesCompany; // Combine filters
  });

  const columns: ColumnDef<Guarantee>[] = [
    {
      accessorKey: "draftNumber",
      header: t("guarantee.draftnumber"),
    },
    {
      accessorKey: "company",
      header: t("guarantee.company"),
    },
    {
      accessorKey: "status",
      header: t("guarantee.status"),
      cell: ({ row }) => {
        const statusKey = row.original.status.replace(/\s+/g, '').toLowerCase();
        let icon = null;
        switch (statusKey) {
          case "active":
            icon = <IconCircleCheckFilled className="h-4 w-4 text-green-500" />;
            break;
          case "inprogress":
            icon = <IconLoader className="h-4 w-4 text-blue-500 animate-spin" />;
            break;
          case "underreview":
            icon = <IconLoader className="h-4 w-4 text-yellow-500 animate-spin" />;
            break;
          case "pendingapproval":
            icon = <IconLoader className="h-4 w-4 text-purple-500 animate-spin" />;
            break;
          default:
            icon = <IconLoader className="h-4 w-4 text-gray-500 animate-spin" />;
        }
        return (
          <Badge variant="outline" className="flex items-center gap-1">
            {icon}
            {t(`guarantee.statusLabels.${statusKey}`)}
          </Badge>
        );
      },
    },
    {
      accessorKey: "goods",
      header: t("guarantee.goods"),
    },
    {
      accessorKey: "createdDate",
      header: t("guarantee.createddate"),
      cell: ({ row }) => (
        <span>{new Date(row.original.createdDate).toLocaleDateString()}</span>
      ),
    },
    {
      accessorKey: "lastModified",
      header: t("guarantee.validUntil"),
      cell: ({ row }) => (
        <span>{new Date(row.original.validUntil).toLocaleDateString()}</span>
      ),
    },
    {
      accessorKey: "createdBy",
      header: t("guarantee.createdby"),
    },
    {
      id: "actions",
      header: t("guarantee.action"),
      cell: ({ row }) => (
        <div className="flex">
          <Link href={`/contracts/guarantee/${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("guarantee.title")}/>
        <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("guarantee.title")}</h2>
                <Button onClick={() => router.push("/contracts/guarantee/new")}>
                  {t("guarantee.new")}
                </Button>
              </div>

              <div className="px-4 lg:px-6">
                <div className="flex items-center gap-4 mb-4 justify-between">
                  <Input
                    placeholder={t("guarantee.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={filteredDrafts} 
                    columns={columns}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
} 