"use client";

import { Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { NONE_SELECT_VALUE, type SelectOption, type StudyContactRow } from "../types";

type StudyContactsEditorProps = {
  contacts: StudyContactRow[];
  personOptions: SelectOption[];
  onChange: (contacts: StudyContactRow[]) => void;
  disabled?: boolean;
};

export function StudyContactsEditor({ contacts, personOptions, onChange, disabled }: StudyContactsEditorProps) {
  const addContact = () => {
    onChange([...contacts, { contactDbId: "", name: "" }]);
  };

  const updateContact = (index: number, personDbId: string) => {
    const option = personOptions.find((entry) => entry.value === personDbId);
    const next = [...contacts];
    next[index] = {
      contactDbId: personDbId,
      name: option?.label ?? personDbId,
    };
    onChange(next);
  };

  const removeContact = (index: number) => {
    onChange(contacts.filter((_, itemIndex) => itemIndex !== index));
  };

  return (
    <div className="md:col-span-2">
      <div className="mb-2 flex items-center justify-between">
        <Label className="text-sm text-slate-700 dark:text-slate-200">研究联系人 (study_contact)</Label>
        <Button type="button" size="sm" variant="outline" className="gap-1.5" onClick={addContact} disabled={disabled}>
          <Plus className="h-3.5 w-3.5" />
          添加联系人
        </Button>
      </div>
      <div className="rounded-lg border border-slate-200 dark:border-slate-800">
        <Table>
          <TableHeader>
            <TableRow className="bg-slate-50 dark:bg-slate-900">
              <TableHead className="text-xs">人员</TableHead>
              <TableHead className="w-16 text-right text-xs">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {contacts.length === 0 ? (
              <TableRow>
                <TableCell colSpan={2} className="py-6 text-center text-sm text-slate-400">
                  暂无联系人
                </TableCell>
              </TableRow>
            ) : (
              contacts.map((contact, index) => (
                <TableRow key={`${contact.contactDbId}-${index}`}>
                  <TableCell>
                    <Select
                      value={contact.contactDbId || NONE_SELECT_VALUE}
                      onValueChange={(value) => {
                        if (value === NONE_SELECT_VALUE) return;
                        updateContact(index, value);
                      }}
                      disabled={disabled}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择 person" />
                      </SelectTrigger>
                      <SelectContent position="popper" className="z-[110] max-h-60">
                        <SelectItem value={NONE_SELECT_VALUE}>请选择人员</SelectItem>
                        {personOptions.map((option) => (
                          <SelectItem key={option.value} value={option.value}>
                            {option.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </TableCell>
                  <TableCell className="text-right">
                    <Button
                      type="button"
                      size="icon"
                      variant="ghost"
                      className="h-7 w-7 text-slate-400 hover:text-red-500"
                      onClick={() => removeContact(index)}
                      disabled={disabled}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
