import { useState, useEffect } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Badge } from '../ui/badge';
import { Textarea } from '../ui/textarea';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '../ui/dialog';
import { Layers, MapPin, Plus, Edit, Trash2 } from 'lucide-react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '../ui/alert-dialog';
import { toast } from 'sonner@2.0.3';

interface SoilTypeItem {
  id: string;
  name: string;
  key: string;
  description: string;
  color: string;
  createdAt: string;
  updatedAt: string;
}

interface PlantingModeItem {
  id: string;
  name: string;
  key: string;
  description: string;
  emoji: string;
  createdAt: string;
  updatedAt: string;
}

const SOIL_TYPES_STORAGE_KEY = 'field_soil_types';
const PLANTING_MODES_STORAGE_KEY = 'field_planting_modes';

// 预设颜色
const PRESET_COLORS = [
  '#f59e0b', '#22c55e', '#f97316', '#3b82f6', 
  '#a855f7', '#ef4444', '#6b7280', '#10b981',
  '#8b5cf6', '#ec4899', '#14b8a6', '#fb923c'
];

// 预设emoji
const PRESET_EMOJIS = [
  '🌾', '🏠', '🍎', '🌊', '🌱', '🌳', '🌻', '🌽',
  '🥬', '🥕', '🍅', '🫑', '🌿', '🪴', '🍇', '🌲'
];

export function FieldClassificationManagement() {
  const [activeTab, setActiveTab] = useState('soil-types');
  
  // 土壤类型
  const [soilTypes, setSoilTypes] = useState<SoilTypeItem[]>([]);
  // 种植模式
  const [plantingModes, setPlantingModes] = useState<PlantingModeItem[]>([]);

  // 对话框状态
  const [showSoilDialog, setShowSoilDialog] = useState(false);
  const [showModeDialog, setShowModeDialog] = useState(false);
  const [editingSoilType, setEditingSoilType] = useState<SoilTypeItem | null>(null);
  const [editingMode, setEditingMode] = useState<PlantingModeItem | null>(null);

  // 表单数据
  const [soilFormData, setSoilFormData] = useState({
    name: '',
    key: '',
    description: '',
    color: '#22c55e',
  });

  const [modeFormData, setModeFormData] = useState({
    name: '',
    key: '',
    description: '',
    emoji: '🌾',
  });

  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deletingItem, setDeletingItem] = useState<{ type: 'soil' | 'mode'; id: string } | null>(null);

  // 加载数据
  useEffect(() => {
    loadSoilTypes();
    loadPlantingModes();
  }, []);

  const loadSoilTypes = () => {
    const stored = localStorage.getItem(SOIL_TYPES_STORAGE_KEY);
    if (stored) {
      setSoilTypes(JSON.parse(stored));
    } else {
      const now = new Date().toISOString();
      const defaultTypes: SoilTypeItem[] = [
        { id: '1', name: '沙土', key: 'sandy', description: '透气性好，保水性差，适合根茎类作物', color: '#f59e0b', createdAt: now, updatedAt: now },
        { id: '2', name: '壤土', key: 'loamy', description: '肥力高，适合多种作物，是最理想的土壤类型', color: '#22c55e', createdAt: now, updatedAt: now },
        { id: '3', name: '粘土', key: 'clay', description: '保水保肥能力强，透气性差', color: '#f97316', createdAt: now, updatedAt: now },
        { id: '4', name: '淤泥土', key: 'silt', description: '有机质丰富，适合水稻等作物', color: '#3b82f6', createdAt: now, updatedAt: now },
        { id: '5', name: '泥炭土', key: 'peat', description: '有机质含量极高，酸性土壤', color: '#a855f7', createdAt: now, updatedAt: now },
        { id: '6', name: '盐碱土', key: 'saline', description: '含盐量高，需要改良后使用', color: '#ef4444', createdAt: now, updatedAt: now },
        { id: '7', name: '其他', key: 'other', description: '其他类型土壤', color: '#6b7280', createdAt: now, updatedAt: now },
      ];
      localStorage.setItem(SOIL_TYPES_STORAGE_KEY, JSON.stringify(defaultTypes));
      setSoilTypes(defaultTypes);
    }
  };

  const loadPlantingModes = () => {
    const stored = localStorage.getItem(PLANTING_MODES_STORAGE_KEY);
    if (stored) {
      setPlantingModes(JSON.parse(stored));
    } else {
      const now = new Date().toISOString();
      const defaultModes: PlantingModeItem[] = [
        { id: '1', name: '露地', key: 'open-field', description: '露天种植，依靠自然条件', emoji: '🌾', createdAt: now, updatedAt: now },
        { id: '2', name: '大棚', key: 'greenhouse', description: '温室大棚种植，可控环境', emoji: '🏠', createdAt: now, updatedAt: now },
        { id: '3', name: '果园', key: 'orchard', description: '果树种植区域', emoji: '🍎', createdAt: now, updatedAt: now },
        { id: '4', name: '水田', key: 'paddy', description: '水稻等水生作物种植', emoji: '🌊', createdAt: now, updatedAt: now },
        { id: '5', name: '旱地', key: 'dryland', description: '旱作物种植区域', emoji: '🌱', createdAt: now, updatedAt: now },
      ];
      localStorage.setItem(PLANTING_MODES_STORAGE_KEY, JSON.stringify(defaultModes));
      setPlantingModes(defaultModes);
    }
  };

  // 土壤类型 - 新增
  const handleAddSoilType = () => {
    setEditingSoilType(null);
    setSoilFormData({ name: '', key: '', description: '', color: '#22c55e' });
    setShowSoilDialog(true);
  };

  // 土壤类型 - 编辑
  const handleEditSoilType = (type: SoilTypeItem) => {
    setEditingSoilType(type);
    setSoilFormData({
      name: type.name,
      key: type.key,
      description: type.description,
      color: type.color,
    });
    setShowSoilDialog(true);
  };

  // 土壤类型 - 保存
  const handleSaveSoilType = () => {
    if (!soilFormData.name.trim()) {
      toast.error('请输入类型名称');
      return;
    }
    if (!soilFormData.key.trim()) {
      toast.error('请输入类型标识');
      return;
    }

    const now = new Date().toISOString();

    if (editingSoilType) {
      // 编辑
      const updatedTypes = soilTypes.map(type =>
        type.id === editingSoilType.id
          ? { ...type, ...soilFormData, updatedAt: now }
          : type
      );
      localStorage.setItem(SOIL_TYPES_STORAGE_KEY, JSON.stringify(updatedTypes));
      setSoilTypes(updatedTypes);
      toast.success('土壤类型更新成功');
    } else {
      // 新增
      const newType: SoilTypeItem = {
        id: `soil-${Date.now()}`,
        ...soilFormData,
        createdAt: now,
        updatedAt: now,
      };
      const updatedTypes = [...soilTypes, newType];
      localStorage.setItem(SOIL_TYPES_STORAGE_KEY, JSON.stringify(updatedTypes));
      setSoilTypes(updatedTypes);
      toast.success('土壤类型添加成功');
    }

    setShowSoilDialog(false);
    
    // 触发自定义事件通知父组件刷新
    window.dispatchEvent(new Event('fieldClassificationUpdated'));
  };

  // 种植模式 - 新增
  const handleAddMode = () => {
    setEditingMode(null);
    setModeFormData({ name: '', key: '', description: '', emoji: '🌾' });
    setShowModeDialog(true);
  };

  // 种植模式 - 编辑
  const handleEditMode = (mode: PlantingModeItem) => {
    setEditingMode(mode);
    setModeFormData({
      name: mode.name,
      key: mode.key,
      description: mode.description,
      emoji: mode.emoji,
    });
    setShowModeDialog(true);
  };

  // 种植模式 - 保存
  const handleSaveMode = () => {
    if (!modeFormData.name.trim()) {
      toast.error('请输入模式名称');
      return;
    }
    if (!modeFormData.key.trim()) {
      toast.error('请输入模式标识');
      return;
    }

    const now = new Date().toISOString();

    if (editingMode) {
      // 编辑
      const updatedModes = plantingModes.map(mode =>
        mode.id === editingMode.id
          ? { ...mode, ...modeFormData, updatedAt: now }
          : mode
      );
      localStorage.setItem(PLANTING_MODES_STORAGE_KEY, JSON.stringify(updatedModes));
      setPlantingModes(updatedModes);
      toast.success('种植模式更新成功');
    } else {
      // 新增
      const newMode: PlantingModeItem = {
        id: `mode-${Date.now()}`,
        ...modeFormData,
        createdAt: now,
        updatedAt: now,
      };
      const updatedModes = [...plantingModes, newMode];
      localStorage.setItem(PLANTING_MODES_STORAGE_KEY, JSON.stringify(updatedModes));
      setPlantingModes(updatedModes);
      toast.success('种植模式添加成功');
    }

    setShowModeDialog(false);
    
    // 触发自定义事件通知父组件刷新
    window.dispatchEvent(new Event('fieldClassificationUpdated'));
  };

  const handleDeleteClick = (type: 'soil' | 'mode', id: string) => {
    setDeletingItem({ type, id });
    setDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    if (!deletingItem) return;

    if (deletingItem.type === 'soil') {
      const item = soilTypes.find(s => s.id === deletingItem.id);
      if (soilTypes.length <= 1) {
        toast.error('至少需要保留一个土壤类型');
        setDeleteDialogOpen(false);
        return;
      }
      const updatedTypes = soilTypes.filter(s => s.id !== deletingItem.id);
      localStorage.setItem(SOIL_TYPES_STORAGE_KEY, JSON.stringify(updatedTypes));
      setSoilTypes(updatedTypes);
      toast.success(`已删除土壤类型：${item?.name}`);
    } else {
      const item = plantingModes.find(m => m.id === deletingItem.id);
      if (plantingModes.length <= 1) {
        toast.error('至少需要保留一个种植模式');
        setDeleteDialogOpen(false);
        return;
      }
      const updatedModes = plantingModes.filter(m => m.id !== deletingItem.id);
      localStorage.setItem(PLANTING_MODES_STORAGE_KEY, JSON.stringify(updatedModes));
      setPlantingModes(updatedModes);
      toast.success(`已删除种植模式：${item?.name}`);
    }

    setDeleteDialogOpen(false);
    setDeletingItem(null);
    
    // 触发自定义事件通知父组件刷新
    window.dispatchEvent(new Event('fieldClassificationUpdated'));
  };

  return (
    <div className="space-y-6">
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full max-w-md grid-cols-2">
          <TabsTrigger value="soil-types" className="flex items-center gap-2">
            <Layers className="w-4 h-4" />
            土壤类型
          </TabsTrigger>
          <TabsTrigger value="planting-modes" className="flex items-center gap-2">
            <MapPin className="w-4 h-4" />
            种植模式
          </TabsTrigger>
        </TabsList>

        <TabsContent value="soil-types" className="mt-6">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <p className="text-sm text-muted-foreground">
                管理地块的土壤类型分类（{soilTypes.length}）
              </p>
              <Button
                className="bg-green-600 hover:bg-green-700"
                onClick={handleAddSoilType}
              >
                <Plus className="w-4 h-4 mr-2" />
                新增类型
              </Button>
            </div>

            <div className="space-y-2">
              {soilTypes.map((soilType) => (
                <Card key={soilType.id} className="p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3 flex-1">
                      <div
                        className="w-4 h-4 rounded-full"
                        style={{ backgroundColor: soilType.color }}
                      />
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{soilType.name}</span>
                          <Badge variant="outline" className="text-xs">
                            {soilType.key}
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground mt-1">
                          {soilType.description}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEditSoilType(soilType)}
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDeleteClick('soil', soilType.id)}
                        disabled={soilTypes.length <= 1}
                      >
                        <Trash2 className="w-4 h-4 text-destructive" />
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}
            </div>

            <Card className="p-4 bg-blue-50 border-blue-200">
              <p className="text-sm text-blue-800">
                💡 提示：土壤类型用于地块分类管理，删除类型前请确保没有地块使用该类型。
              </p>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="planting-modes" className="mt-6">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <p className="text-sm text-muted-foreground">
                管理地块的种植模式分类（{plantingModes.length}）
              </p>
              <Button
                className="bg-green-600 hover:bg-green-700"
                onClick={handleAddMode}
              >
                <Plus className="w-4 h-4 mr-2" />
                新增模式
              </Button>
            </div>

            <div className="space-y-2">
              {plantingModes.map((mode) => (
                <Card key={mode.id} className="p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3 flex-1">
                      <div className="text-2xl">{mode.emoji}</div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{mode.name}</span>
                          <Badge variant="outline" className="text-xs">
                            {mode.key}
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground mt-1">
                          {mode.description}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEditMode(mode)}
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDeleteClick('mode', mode.id)}
                        disabled={plantingModes.length <= 1}
                      >
                        <Trash2 className="w-4 h-4 text-destructive" />
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}
            </div>

            <Card className="p-4 bg-blue-50 border-blue-200">
              <p className="text-sm text-blue-800">
                💡 提示：种植模式用于地块分类管理，删除模式前请确保没有地块使用该模式。
              </p>
            </Card>
          </div>
        </TabsContent>
      </Tabs>

      {/* 土壤类型新增/编辑对话框 */}
      <Dialog open={showSoilDialog} onOpenChange={setShowSoilDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editingSoilType ? '编辑土壤类型' : '新增土壤类型'}</DialogTitle>
            <DialogDescription>
              {editingSoilType ? '修改土壤类型信息' : '添加新的土壤类型'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="soil-key">类型标识 *</Label>
              <Input
                id="soil-key"
                placeholder="如：sandy"
                value={soilFormData.key}
                onChange={(e) => setSoilFormData({ ...soilFormData, key: e.target.value.toLowerCase() })}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="soil-name">类型名称 *</Label>
              <Input
                id="soil-name"
                placeholder="如：沙土"
                value={soilFormData.name}
                onChange={(e) => setSoilFormData({ ...soilFormData, name: e.target.value })}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="soil-description">描述</Label>
              <Textarea
                id="soil-description"
                placeholder="请输入类型描述..."
                rows={3}
                value={soilFormData.description}
                onChange={(e) => setSoilFormData({ ...soilFormData, description: e.target.value })}
              />
            </div>

            <div className="space-y-2">
              <Label>颜色标识</Label>
              <div className="flex gap-2 flex-wrap">
                {PRESET_COLORS.map((color, index) => (
                  <button
                    key={`color-${index}`}
                    type="button"
                    className={`w-8 h-8 rounded-full border-2 ${
                      soilFormData.color === color ? 'border-green-600' : 'border-gray-300'
                    }`}
                    style={{ backgroundColor: color }}
                    onClick={() => setSoilFormData({ ...soilFormData, color })}
                  />
                ))}
              </div>
              <div className="flex items-center gap-2 mt-2">
                <Input
                  type="color"
                  value={soilFormData.color}
                  onChange={(e) => setSoilFormData({ ...soilFormData, color: e.target.value })}
                  className="w-20 h-10"
                />
                <span className="text-sm text-muted-foreground">{soilFormData.color}</span>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowSoilDialog(false)}>
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveSoilType}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 种植模式新增/编辑对话框 */}
      <Dialog open={showModeDialog} onOpenChange={setShowModeDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editingMode ? '编辑种植模式' : '新增种植模式'}</DialogTitle>
            <DialogDescription>
              {editingMode ? '修改种植模式信息' : '添加新的种植模式'}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="mode-key">模式标识 *</Label>
              <Input
                id="mode-key"
                placeholder="如：open-field"
                value={modeFormData.key}
                onChange={(e) => setModeFormData({ ...modeFormData, key: e.target.value.toLowerCase() })}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="mode-name">模式名称 *</Label>
              <Input
                id="mode-name"
                placeholder="如：露地"
                value={modeFormData.name}
                onChange={(e) => setModeFormData({ ...modeFormData, name: e.target.value })}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="mode-description">描述</Label>
              <Textarea
                id="mode-description"
                placeholder="请输入模式描述..."
                rows={3}
                value={modeFormData.description}
                onChange={(e) => setModeFormData({ ...modeFormData, description: e.target.value })}
              />
            </div>

            <div className="space-y-2">
              <Label>图标选择</Label>
              <div className="flex gap-2 flex-wrap">
                {PRESET_EMOJIS.map((emoji, index) => (
                  <button
                    key={`emoji-${index}`}
                    type="button"
                    className={`w-10 h-10 text-2xl rounded border-2 ${
                      modeFormData.emoji === emoji ? 'border-green-600 bg-green-50' : 'border-gray-300'
                    }`}
                    onClick={() => setModeFormData({ ...modeFormData, emoji })}
                  >
                    {emoji}
                  </button>
                ))}
              </div>
              <div className="flex items-center gap-2 mt-2">
                <Input
                  type="text"
                  value={modeFormData.emoji}
                  onChange={(e) => setModeFormData({ ...modeFormData, emoji: e.target.value })}
                  className="w-20 h-10 text-center text-2xl"
                  maxLength={2}
                />
                <span className="text-sm text-muted-foreground">自定义图标</span>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowModeDialog(false)}>
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveMode}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              删除后，使用该分类的地块需要重新设置分类。此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setDeletingItem(null)}>取消</AlertDialogCancel>
            <AlertDialogAction
              className="bg-red-600 hover:bg-red-700"
              onClick={confirmDelete}
            >
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
