import { LoaderCircle } from 'lucide-react';
import type { Dispatch, SetStateAction } from 'react';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import type { ProcurementMaterial } from '@/types';

const SHORT_FIELDS: Array<{ key: keyof ProcurementMaterial; label: string; type?: string }> = [
  { key: 'material_name', label: '材料名称' },
  { key: 'specification', label: '规格型号' },
  { key: 'quantity', label: '数量', type: 'number' },
  { key: 'unit', label: '单位' },
  { key: 'brand', label: '品牌' },
  { key: 'batch_id', label: '批次ID' },
  { key: 'source_file', label: '来源文件' },
  { key: 'technical_standard', label: '技术标准' },
  { key: 'invoice_type', label: '发票类型' },
  { key: 'warranty_period', label: '质保期' },
  { key: 'deadline', label: '交货期限' },
  { key: 'delivery_address', label: '收货地址' },
];

const LONG_FIELDS: Array<{ key: keyof ProcurementMaterial; label: string }> = [
  { key: 'material_requirement', label: '材质要求' },
  { key: 'technical_requirement', label: '技术要求' },
  { key: 'test_requirement', label: '检验要求' },
  { key: 'applicable_conditions', label: '适用条件' },
  { key: 'acceptance_note', label: '验收说明' },
  { key: 'remarks', label: '备注' },
];

export interface MaterialEditDialogProps {
  /** 非 null 即视为打开 */
  editingMaterial: ProcurementMaterial | null;
  /** 当前编辑表单值；调用方负责持有此 state */
  editForm: Partial<ProcurementMaterial>;
  onEditFormChange: Dispatch<SetStateAction<Partial<ProcurementMaterial>>>;
  onClose: () => void;
  onSave: () => void;
  isSaving?: boolean;
}

export function MaterialEditDialog({
  editingMaterial,
  editForm,
  onEditFormChange,
  onClose,
  onSave,
  isSaving = false,
}: MaterialEditDialogProps) {
  const open = editingMaterial !== null;

  return (
    <Dialog open={open} onOpenChange={next => { if (!next) onClose(); }}>
      <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>编辑材料</DialogTitle>
          <DialogDescription>修改材料信息后点击保存。</DialogDescription>
        </DialogHeader>
        {editingMaterial && (
          <div className="grid grid-cols-2 gap-4 py-2">
            {SHORT_FIELDS.map(field => (
              <div key={field.key} className="space-y-1.5">
                <Label htmlFor={`edit-${field.key}`} className="text-sm">{field.label}</Label>
                <Input
                  id={`edit-${field.key}`}
                  type={field.type ?? 'text'}
                  value={(editForm[field.key] ?? '') as string | number}
                  onChange={e =>
                    onEditFormChange(prev => ({
                      ...prev,
                      [field.key]: field.type === 'number' ? Number(e.target.value) : e.target.value,
                    }))
                  }
                />
              </div>
            ))}
            {LONG_FIELDS.map(field => (
              <div key={field.key} className="col-span-2 space-y-1.5">
                <Label htmlFor={`edit-${field.key}`} className="text-sm">{field.label}</Label>
                <Textarea
                  id={`edit-${field.key}`}
                  rows={2}
                  value={(editForm[field.key] as string) ?? ''}
                  onChange={e =>
                    onEditFormChange(prev => ({ ...prev, [field.key]: e.target.value }))
                  }
                />
              </div>
            ))}
          </div>
        )}
        <DialogFooter>
          <Button variant="outline" onClick={onClose}>取消</Button>
          <Button onClick={onSave} disabled={isSaving}>
            {isSaving ? <LoaderCircle className="h-4 w-4 animate-spin mr-1" /> : null}
            保存
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
