import { useState } from 'react';
import { FieldTag } from '../../types/field';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '../ui/alert-dialog';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Badge } from '../ui/badge';
import { Card } from '../ui/card';
import { Edit, Trash2 } from 'lucide-react';

interface FieldTagManagementProps {
  tags: FieldTag[];
  onSave: (tag: FieldTag) => void;
  onDelete: (id: string) => void;
}

export function FieldTagManagement({ tags, onSave, onDelete }: FieldTagManagementProps) {
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<string>('');
  const [editingTag, setEditingTag] = useState<FieldTag | null>(null);
  const [name, setName] = useState('');
  const [color, setColor] = useState('#22c55e');
  const [description, setDescription] = useState('');

  const handleDeleteClick = (id: string) => {
    setDeletingId(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    onDelete(deletingId);
    setDeleteDialogOpen(false);
    setDeletingId('');
  };

  const presetColors = [
    '#22c55e', '#3b82f6', '#8b5cf6', '#f59e0b', '#ef4444',
    '#06b6d4', '#ec4899', '#6366f1', '#14b8a6', '#f97316'
  ];

  const handleSave = () => {
    if (!name.trim()) return;

    const tag: FieldTag = {
      id: editingTag?.id || `tag-${Date.now()}`,
      name: name.trim(),
      color,
      description: description.trim(),
      createdAt: editingTag?.createdAt || new Date().toISOString(),
    };

    onSave(tag);
    resetForm();
  };

  const resetForm = () => {
    setEditingTag(null);
    setName('');
    setColor('#22c55e');
    setDescription('');
  };

  const startEdit = (tag: FieldTag) => {
    setEditingTag(tag);
    setName(tag.name);
    setColor(tag.color);
    setDescription(tag.description || '');
  };

  return (
    <div className="space-y-6">
      {/* 添加/编辑表单 */}
      <Card className="p-4">
        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="tagName">标签名称</Label>
            <Input
              id="tagName"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="输入标签名称"
            />
          </div>

          <div className="space-y-2">
            <Label>标签颜色</Label>
            <div className="flex flex-wrap gap-2">
              {presetColors.map((presetColor) => (
                <button
                  key={presetColor}
                  type="button"
                  className={`w-8 h-8 rounded-full border-2 ${
                    color === presetColor ? 'border-primary' : 'border-transparent'
                  }`}
                  style={{ backgroundColor: presetColor }}
                  onClick={() => setColor(presetColor)}
                />
              ))}
              <input
                type="color"
                value={color}
                onChange={(e) => setColor(e.target.value)}
                className="w-8 h-8 rounded-full cursor-pointer"
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="tagDescription">标签描述</Label>
            <Input
              id="tagDescription"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="输入标签描述（可选）"
            />
          </div>

          <div className="space-y-2">
            <Label>预览</Label>
            <div>
              <Badge style={{ backgroundColor: color, color: 'white' }}>
                {name || '标签示例'}
              </Badge>
            </div>
          </div>

          <div className="flex gap-2">
            <Button onClick={handleSave} disabled={!name.trim()} className="bg-green-600 hover:bg-green-700">
              {editingTag ? '更新标签' : '添加标签'}
            </Button>
            {editingTag && (
              <Button variant="outline" onClick={resetForm}>
                取消编辑
              </Button>
            )}
          </div>
        </div>
      </Card>

      {/* 标签列表 */}
      <div className="space-y-2">
        <Label>已有标签 ({tags.length})</Label>
        {tags.length === 0 ? (
          <div className="text-center text-muted-foreground py-8 border rounded-md">
            暂无标签，请添加
          </div>
        ) : (
          <div className="grid grid-cols-1 gap-2 max-h-[300px] overflow-y-auto">
            {tags.map((tag) => (
              <Card key={tag.id} className="p-3">
                <div className="flex items-center justify-between">
                  <div className="flex-1">
                    <Badge style={{ backgroundColor: tag.color, color: 'white' }}>
                      {tag.name}
                    </Badge>
                    {tag.description && (
                      <p className="text-xs text-muted-foreground mt-1">{tag.description}</p>
                    )}
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => startEdit(tag)}
                    >
                      <Edit className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDeleteClick(tag.id)}
                    >
                      <Trash2 className="w-4 h-4 text-destructive" />
                    </Button>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>

      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除这个标签吗？此操作无法撤销，所有使用该标签的地块都将移除此标签。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              className="bg-red-600 hover:bg-red-700"
              onClick={confirmDelete}
            >
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
