import React, { useState, useEffect } from 'react';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Card, CardContent } from '@d8d/shared-ui-components/components/ui/card';
import { Label } from '@d8d/shared-ui-components/components/ui/label';
import { Textarea } from '@d8d/shared-ui-components/components/ui/textarea';
import { Switch } from '@d8d/shared-ui-components/components/ui/switch';
import { Plus, Trash2, MessageSquare } from 'lucide-react';
import { toast } from 'sonner';

export interface RemarkItem {
  remarkContent: string;
  isSpecialNeeds: number;
  operatorId: number;
  tempId?: string; // 临时ID用于React key
}

export interface RemarkManagementProps {
  value?: RemarkItem[];
  onChange?: (remarks: RemarkItem[]) => void;
  maxRemarks?: number;
  currentUserId: number; // 当前登录用户ID，作为默认操作人
}

export const RemarkManagement: React.FC<RemarkManagementProps> = ({
  value = [],
  onChange,
  maxRemarks = 10,
  currentUserId,
}) => {
  const [remarks, setRemarks] = useState<RemarkItem[]>(value);

  // 同步外部value变化
  useEffect(() => {
    setRemarks(value);
  }, [value]);

  const handleAddRemark = () => {
    if (remarks.length >= maxRemarks) {
      toast.warning(`最多只能添加 ${maxRemarks} 条备注`);
      return;
    }

    const newRemark: RemarkItem = {
      remarkContent: '',
      isSpecialNeeds: 0,
      operatorId: currentUserId,
      tempId: `temp-${Date.now()}-${Math.random()}`,
    };

    const newRemarks = [...remarks, newRemark];
    setRemarks(newRemarks);
    onChange?.(newRemarks);
  };

  const handleRemoveRemark = (index: number) => {
    const newRemarks = remarks.filter((_, i) => i !== index);
    setRemarks(newRemarks);
    onChange?.(newRemarks);
  };

  const handleFieldChange = (index: number, field: keyof RemarkItem, value: string | number) => {
    const newRemarks = [...remarks];
    newRemarks[index] = { ...newRemarks[index], [field]: value };
    setRemarks(newRemarks);
    onChange?.(newRemarks);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <Label>备注管理</Label>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={handleAddRemark}
          disabled={remarks.length >= maxRemarks}
          data-testid="add-remark-button"
        >
          <Plus className="h-4 w-4 mr-2" />
          添加备注
        </Button>
      </div>

      {remarks.length === 0 ? (
        <Card>
          <CardContent className="pt-6">
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <MessageSquare className="h-12 w-12 text-muted-foreground mb-4" />
              <p className="text-sm text-muted-foreground">暂无备注信息</p>
              <p className="text-xs text-muted-foreground mt-1">点击"添加备注"按钮添加备注信息</p>
            </div>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-4">
          {remarks.map((remark, index) => (
            <Card key={remark.tempId || index} className="relative">
              <CardContent className="pt-6">
                <div className="absolute top-4 right-4">
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => handleRemoveRemark(index)}
                    data-testid={`remove-remark-${index}`}
                  >
                    <Trash2 className="h-4 w-4 text-destructive" />
                  </Button>
                </div>

                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor={`remarkContent-${index}`}>备注内容 *</Label>
                    <Textarea
                      id={`remarkContent-${index}`}
                      value={remark.remarkContent}
                      onChange={(e) => handleFieldChange(index, 'remarkContent', e.target.value)}
                      placeholder="请输入备注内容..."
                      rows={3}
                      data-testid={`remark-content-textarea-${index}`}
                    />
                  </div>

                  <div className="flex items-center space-x-2">
                    <Switch
                      checked={remark.isSpecialNeeds === 1}
                      onCheckedChange={(checked) => handleFieldChange(index, 'isSpecialNeeds', checked ? 1 : 0)}
                      data-testid={`special-needs-switch-${index}`}
                    />
                    <Label htmlFor={`isSpecialNeeds-${index}`}>标记为特殊需求</Label>
                  </div>

                  <div className="text-xs text-muted-foreground">
                    <p>操作人ID：{remark.operatorId}</p>
                    {remark.isSpecialNeeds === 1 && (
                      <p className="text-amber-600">此备注已标记为特殊需求，需要特别关注</p>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <div className="text-xs text-muted-foreground">
        <p>• 最多可添加 {maxRemarks} 条备注</p>
        <p>• 备注内容为必填项</p>
        <p>• 特殊需求标记用于标识需要特别关注的备注</p>
        <p>• 操作人ID自动设置为当前登录用户</p>
      </div>
    </div>
  );
};

export default RemarkManagement;