import { useRsi } from "../../../hooks/useRsi"
import { ColumnType, type Column } from "../types"
import type { Fields } from "../../../types"
import {
  Card,
  CardContent,
  CardHeader,
} from "@/components/ui/card"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion"
import { Check } from "lucide-react"

type TemplateColumnProps<T extends string> = {
  column: Column<T>
  onChange: (value: T, columnIndex: number) => void
  onSubChange: (value: string, columnIndex: number, entry: string) => void
}

const getAccordionTitle = <T extends string>(fields: Fields<T>, column: Column<T>, translations: any) => {
  const field = fields.find((f) => "value" in column && f.key === column.value)
  if (!field) return ""
  return `${translations.matchColumnsStep.matchDropdownTitle} ${field.label} (${
    "matchedOptions" in column ? column.matchedOptions.filter((option) => !option.value).length : 0
  } ${translations.matchColumnsStep.unmatched})`
}

export const TemplateColumn = <T extends string>({ column, onChange, onSubChange }: TemplateColumnProps<T>) => {
  const { translations, fields } = useRsi<T>()
  const isIgnored = column.type === ColumnType.ignored
  const isChecked =
    column.type === ColumnType.matched ||
    column.type === ColumnType.matchedCheckbox ||
    column.type === ColumnType.matchedSelectOptions
  const isSelect = "matchedOptions" in column
  const selectOptions = fields.map(({ label, key }) => ({ value: key, label }))
  const selectValue = column.type === ColumnType.empty ? undefined : 
    selectOptions.find(({ value }) => "value" in column && column.value === value)?.value

  if (isIgnored) {
    return null
  }

  return (
    <Card className="h-full">
      <CardHeader className="flex flex-row items-center justify-between space-x-2 p-4">
        <div className="flex-1">
          <Select
            key={`select-${column.index}-${("value" in column ? column.value : "empty")}`}
            value={selectValue}
            onValueChange={(value) => onChange(value as T, column.index)}
          >
            <SelectTrigger className="w-full">
              <SelectValue placeholder={translations.matchColumnsStep.selectPlaceholder} />
            </SelectTrigger>
            <SelectContent 
              side="bottom"
              align="start"
              className="z-[1500]"
            >
              {selectOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        {isChecked && (
          <div className="flex h-8 w-8 items-center justify-center rounded-full border border-green-700 bg-green-300 dark:bg-green-900/20">
            <Check className="h-4 w-4 text-green-700 dark:text-green-500" />
          </div>
        )}
      </CardHeader>
      {isSelect && (
        <CardContent className="p-4">
          <Accordion type="multiple" className="w-full">
            <AccordionItem value="options" className="border-none">
              <AccordionTrigger className="py-2 text-sm hover:no-underline">
                {getAccordionTitle(fields, column, translations)}
              </AccordionTrigger>
              <AccordionContent>
                <div className="space-y-2">
                  {column.matchedOptions.map((option) => (
                    <div key={option.entry} className="space-y-1">
                      <p className="text-sm text-muted-foreground">
                        {option.entry}
                      </p>
                      <Select
                        value={option.value}
                        onValueChange={(value) => onSubChange(value, column.index, option.entry!)}
                      >
                        <SelectTrigger className="w-full">
                          <SelectValue placeholder={translations.matchColumnsStep.subSelectPlaceholder} />
                        </SelectTrigger>
                        <SelectContent 
                          side="bottom"
                          align="start"
                          className="z-[1000]"
                        >
                          {(() => {
                            const field = fields.find((f) => "value" in column && f.key === column.value)
                            if (!field || !("fieldType" in field) || !("options" in field.fieldType)) return null
                            return field.fieldType.options.map((option) => (
                              <SelectItem key={option.value} value={option.value}>
                                {option.label}
                              </SelectItem>
                            ))
                          })()}
                        </SelectContent>
                      </Select>
                    </div>
                  ))}
                </div>
              </AccordionContent>
            </AccordionItem>
          </Accordion>
        </CardContent>
      )}
    </Card>
  )
}
