"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
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,
  DialogBody,
  DialogContent,
  DialogFooter,
} from "@/components/common/shadcn-enhanced";
import { updateListRow } from "../api";
import { LIST_TYPE_OPTIONS, NONE_SELECT_VALUE, type ListRecord, type SelectOption } from "../types";

type ListMetaDialogProps = {
  open: boolean;
  record: ListRecord;
  personOptions: SelectOption[];
  onOpenChange: (open: boolean) => void;
  onSaved: (record: ListRecord) => void;
};

export function ListMetaDialog({ open, record, personOptions, onOpenChange, onSaved }: ListMetaDialogProps) {
  const [form, setForm] = useState({
    listName: "",
    listType: "",
    listDescription: "",
    listSource: "",
    listOwnerName: "",
    listOwnerPersonDbId: NONE_SELECT_VALUE,
  });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    setForm({
      listName: record.listName ?? "",
      listType: record.listType ?? "",
      listDescription: record.listDescription ?? "",
      listSource: record.listSource ?? "",
      listOwnerName: record.listOwnerName ?? "",
      listOwnerPersonDbId: record.listOwnerPersonDbId || NONE_SELECT_VALUE,
    });
    setError(null);
  }, [open, record]);

  const updateField = (key: keyof typeof form, value: string) => {
    setForm((current) => ({ ...current, [key]: value }));
  };

  const handleSave = async () => {
    setSaving(true);
    setError(null);
    try {
      const updated = await updateListRow(record.id, form, record.data ?? []);
      onSaved(updated);
      onOpenChange(false);
    } catch (event) {
      setError(event instanceof Error ? event.message : "保存失败");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent title="编辑列表基本信息" defaultWidth={720} defaultHeight={560} minHeight={420}>
        <DialogBody>
          <p className="mb-3 text-sm text-muted-foreground">修改 list 主表字段，不会影响已有 list_item</p>
          {error ? (
            <div className="mb-3 rounded-lg border border-destructive/20 bg-destructive/10 px-3 py-2 text-sm text-destructive">
              {error}
            </div>
          ) : null}
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="md:col-span-2">
              <Label htmlFor="edit-listName" className="mb-1.5 block text-sm">
                列表名称<span className="ml-0.5 text-red-500">*</span>
              </Label>
              <Input
                id="edit-listName"
                value={form.listName}
                onChange={(event) => updateField("listName", event.target.value)}
              />
            </div>
            <div>
              <Label htmlFor="edit-listType" className="mb-1.5 block text-sm">
                列表类型<span className="ml-0.5 text-red-500">*</span>
              </Label>
              <Select value={form.listType} onValueChange={(value) => updateField("listType", value)}>
                <SelectTrigger id="edit-listType">
                  <SelectValue placeholder="请选择列表类型" />
                </SelectTrigger>
                <SelectContent position="item-aligned">
                  {LIST_TYPE_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="edit-listSource" className="mb-1.5 block text-sm">列表来源</Label>
              <Input
                id="edit-listSource"
                value={form.listSource}
                onChange={(event) => updateField("listSource", event.target.value)}
              />
            </div>
            <div>
              <Label htmlFor="edit-listOwnerName" className="mb-1.5 block text-sm">Owner 名称</Label>
              <Input
                id="edit-listOwnerName"
                value={form.listOwnerName}
                onChange={(event) => updateField("listOwnerName", event.target.value)}
              />
            </div>
            <div>
              <Label htmlFor="edit-listOwnerPersonDbId" className="mb-1.5 block text-sm">Owner 人员</Label>
              <Select
                value={form.listOwnerPersonDbId}
                onValueChange={(value) => updateField("listOwnerPersonDbId", value)}
              >
                <SelectTrigger id="edit-listOwnerPersonDbId">
                  <SelectValue placeholder="不绑定人员" />
                </SelectTrigger>
                <SelectContent position="item-aligned">
                  <SelectItem value={NONE_SELECT_VALUE}>不绑定人员</SelectItem>
                  {personOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="md:col-span-2">
              <Label htmlFor="edit-listDescription" className="mb-1.5 block text-sm">列表描述</Label>
              <Textarea
                id="edit-listDescription"
                value={form.listDescription}
                onChange={(event) => updateField("listDescription", event.target.value)}
                rows={3}
                className="resize-none"
              />
            </div>
          </div>
        </DialogBody>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
            取消
          </Button>
          <Button onClick={handleSave} disabled={saving}>
            {saving ? "保存中..." : "保存"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
