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 { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Textarea } from '@d8d/shared-ui-components/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { Plus, Trash2, Calendar, User } from 'lucide-react';
import { toast } from 'sonner';

export interface VisitItem {
  visitDate: string; // ISO格式日期字符串
  visitType: string;
  visitContent: string;
  visitResult?: string;
  nextVisitDate?: string; // ISO格式日期字符串
  visitorId: number;
  tempId?: string; // 临时ID用于React key
}

export interface VisitManagementProps {
  value?: VisitItem[];
  onChange?: (visits: VisitItem[]) => void;
  maxVisits?: number;
  currentUserId: number; // 当前登录用户ID，作为默认回访人
  visitTypes?: string[];
}

export const VisitManagement: React.FC<VisitManagementProps> = ({
  value = [],
  onChange,
  maxVisits = 10,
  currentUserId,
  visitTypes = ['电话回访', '上门回访', '视频回访', '微信回访', '其他'],
}) => {
  const [visits, setVisits] = useState<VisitItem[]>(value);

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

  const handleAddVisit = () => {
    if (visits.length >= maxVisits) {
      toast.warning(`最多只能添加 ${maxVisits} 条回访记录`);
      return;
    }

    const today = new Date();
    const nextMonth = new Date(today);
    nextMonth.setMonth(nextMonth.getMonth() + 1);

    const newVisit: VisitItem = {
      visitDate: today.toISOString().split('T')[0], // YYYY-MM-DD格式
      visitType: visitTypes[0],
      visitContent: '',
      visitorId: currentUserId,
      tempId: `temp-${Date.now()}-${Math.random()}`,
    };

    const newVisits = [...visits, newVisit];
    setVisits(newVisits);
    onChange?.(newVisits);
  };

  const handleRemoveVisit = (index: number) => {
    const newVisits = visits.filter((_, i) => i !== index);
    setVisits(newVisits);
    onChange?.(newVisits);
  };

  const handleFieldChange = (index: number, field: keyof VisitItem, value: string | number) => {
    const newVisits = [...visits];
    newVisits[index] = { ...newVisits[index], [field]: value };
    setVisits(newVisits);
    onChange?.(newVisits);
  };

  const formatDateForInput = (dateString?: string) => {
    if (!dateString) return '';
    try {
      return dateString.split('T')[0]; // 转换为YYYY-MM-DD格式
    } catch {
      return '';
    }
  };

  const validateVisitDate = (dateString: string) => {
    const visitDate = new Date(dateString);
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    return visitDate <= today;
  };

  const validateNextVisitDate = (visitDate: string, nextVisitDate?: string) => {
    if (!nextVisitDate) return true;

    const visit = new Date(visitDate);
    const nextVisit = new Date(nextVisitDate);

    return nextVisit > visit;
  };

  const getVisitTypeLabel = (visitType: string) => {
    return visitType;
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <Label>回访记录管理</Label>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={handleAddVisit}
          disabled={visits.length >= maxVisits}
          data-testid="add-visit-button"
        >
          <Plus className="h-4 w-4 mr-2" />
          添加回访记录
        </Button>
      </div>

      {visits.length === 0 ? (
        <Card>
          <CardContent className="pt-6">
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <Calendar 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">
          {visits.map((visit, index) => (
            <Card key={visit.tempId || index} className="relative">
              <CardContent className="pt-6">
                <div className="absolute top-4 right-4">
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => handleRemoveVisit(index)}
                    data-testid={`remove-visit-${index}`}
                  >
                    <Trash2 className="h-4 w-4 text-destructive" />
                  </Button>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor={`visitDate-${index}`}>回访日期 *</Label>
                    <Input
                      id={`visitDate-${index}`}
                      type="date"
                      value={formatDateForInput(visit.visitDate)}
                      onChange={(e) => handleFieldChange(index, 'visitDate', e.target.value)}
                      data-testid={`visit-date-input-${index}`}
                    />
                    {visit.visitDate && !validateVisitDate(visit.visitDate) && (
                      <p className="text-xs text-destructive">回访日期不能晚于今天</p>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor={`visitType-${index}`}>回访类型 *</Label>
                    <Select
                      value={visit.visitType}
                      onValueChange={(value) => handleFieldChange(index, 'visitType', value)}
                    >
                      <SelectTrigger data-testid={`visit-type-select-${index}`}>
                        <SelectValue placeholder="选择回访类型" />
                      </SelectTrigger>
                      <SelectContent>
                        {visitTypes.map((type) => (
                          <SelectItem key={type} value={type}>
                            {getVisitTypeLabel(type)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2 md:col-span-2">
                    <Label htmlFor={`visitContent-${index}`}>回访内容 *</Label>
                    <Textarea
                      id={`visitContent-${index}`}
                      value={visit.visitContent}
                      onChange={(e) => handleFieldChange(index, 'visitContent', e.target.value)}
                      placeholder="请输入回访内容..."
                      rows={3}
                      data-testid={`visit-content-textarea-${index}`}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor={`visitResult-${index}`}>回访结果</Label>
                    <Input
                      id={`visitResult-${index}`}
                      value={visit.visitResult || ''}
                      onChange={(e) => handleFieldChange(index, 'visitResult', e.target.value)}
                      placeholder="例如：良好、需要跟进等"
                      data-testid={`visit-result-input-${index}`}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor={`nextVisitDate-${index}`}>下次回访日期</Label>
                    <Input
                      id={`nextVisitDate-${index}`}
                      type="date"
                      value={formatDateForInput(visit.nextVisitDate)}
                      onChange={(e) => handleFieldChange(index, 'nextVisitDate', e.target.value)}
                      data-testid={`next-visit-date-input-${index}`}
                    />
                    {visit.visitDate && visit.nextVisitDate && !validateNextVisitDate(visit.visitDate, visit.nextVisitDate) && (
                      <p className="text-xs text-destructive">下次回访日期应晚于本次回访日期</p>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor={`visitorId-${index}`}>回访人ID</Label>
                    <div className="flex items-center space-x-2">
                      <User className="h-4 w-4 text-muted-foreground" />
                      <Input
                        id={`visitorId-${index}`}
                        type="number"
                        value={visit.visitorId}
                        onChange={(e) => handleFieldChange(index, 'visitorId', parseInt(e.target.value) || currentUserId)}
                        data-testid={`visitor-id-input-${index}`}
                      />
                    </div>
                    <p className="text-xs text-muted-foreground">当前登录用户ID：{currentUserId}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <div className="text-xs text-muted-foreground">
        <p>• 最多可添加 {maxVisits} 条回访记录</p>
        <p>• 回访日期不能晚于今天</p>
        <p>• 下次回访日期应晚于本次回访日期</p>
        <p>• 回访内容为必填项</p>
      </div>
    </div>
  );
};

export default VisitManagement;