import { useState, useEffect } from 'react';
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../ui/select';
import { Checkbox } from '../ui/checkbox';
import { Field, FieldTag } from '../../types/field';
import { BarChart3, Filter, Download, Search, PieChart, BarChart, Trash2 } from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  BarChart as RechartsBarChart,
  Bar,
  PieChart as RechartsPieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';

interface SoilType {
  id: string;
  name: string;
  key: string;
  color: string;
}

interface PlantingMode {
  id: string;
  name: string;
  key: string;
  emoji: string;
}

interface FilterCondition {
  soilTypes: string[];
  plantingModes: string[];
  tags: string[];
  minArea: string;
  maxArea: string;
  keyword: string;
}

interface StatisticsResult {
  totalCount: number;
  totalArea: number;
  avgArea: number;
  maxArea: number;
  minArea: number;
  soilTypeDistribution: { name: string; count: number; area: number; color: string }[];
  plantingModeDistribution: { name: string; count: number; area: number; emoji: string }[];
  tagDistribution: { name: string; count: number; color: string }[];
}

const COLORS = ['#22c55e', '#3b82f6', '#f59e0b', '#a855f7', '#ef4444', '#14b8a6', '#f97316', '#8b5cf6'];

export function FieldStatistics() {
  const [fields, setFields] = useState<Field[]>([]);
  const [tags, setTags] = useState<FieldTag[]>([]);
  const [soilTypes, setSoilTypes] = useState<SoilType[]>([]);
  const [plantingModes, setPlantingModes] = useState<PlantingMode[]>([]);
  
  const [filters, setFilters] = useState<FilterCondition>({
    soilTypes: [],
    plantingModes: [],
    tags: [],
    minArea: '',
    maxArea: '',
    keyword: '',
  });

  const [statistics, setStatistics] = useState<StatisticsResult | null>(null);
  const [chartType, setChartType] = useState<'bar' | 'pie'>('bar');

  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    // 加载地块数据
    const fieldsData = localStorage.getItem('smart_agriculture_fields');
    if (fieldsData) {
      setFields(JSON.parse(fieldsData));
    }

    // 加载标签数据
    const tagsData = localStorage.getItem('smart_agriculture_custom_tags');
    if (tagsData) {
      setTags(JSON.parse(tagsData));
    }

    // 加载土壤类型
    const soilTypesData = localStorage.getItem('field_soil_types');
    if (soilTypesData) {
      setSoilTypes(JSON.parse(soilTypesData));
    }

    // 加载种植模式
    const plantingModesData = localStorage.getItem('field_planting_modes');
    if (plantingModesData) {
      setPlantingModes(JSON.parse(plantingModesData));
    }
  };

  const handleFilterChange = (key: keyof FilterCondition, value: any) => {
    setFilters({ ...filters, [key]: value });
  };

  const toggleArrayFilter = (key: 'soilTypes' | 'plantingModes' | 'tags', value: string) => {
    const currentArray = filters[key];
    const newArray = currentArray.includes(value)
      ? currentArray.filter(v => v !== value)
      : [...currentArray, value];
    setFilters({ ...filters, [key]: newArray });
  };

  const clearFilters = () => {
    setFilters({
      soilTypes: [],
      plantingModes: [],
      tags: [],
      minArea: '',
      maxArea: '',
      keyword: '',
    });
    setStatistics(null);
    toast.success('筛选条件已清空');
  };

  const executeQuery = () => {
    // 应用筛选条件
    let filteredFields = [...fields];

    // 关键词筛选
    if (filters.keyword) {
      const keyword = filters.keyword.toLowerCase();
      filteredFields = filteredFields.filter(f =>
        f.name.toLowerCase().includes(keyword) ||
        f.code.toLowerCase().includes(keyword) ||
        f.location?.toLowerCase().includes(keyword)
      );
    }

    // 土壤类型筛选
    if (filters.soilTypes.length > 0) {
      filteredFields = filteredFields.filter(f =>
        filters.soilTypes.includes(f.soilType)
      );
    }

    // 种植模式筛选
    if (filters.plantingModes.length > 0) {
      filteredFields = filteredFields.filter(f =>
        filters.plantingModes.includes(f.plantingMode)
      );
    }

    // 标签筛选
    if (filters.tags.length > 0) {
      filteredFields = filteredFields.filter(f =>
        filters.tags.some(tag => f.tags.includes(tag))
      );
    }

    // 面积范围筛选
    if (filters.minArea) {
      const minArea = parseFloat(filters.minArea);
      filteredFields = filteredFields.filter(f => f.area >= minArea);
    }
    if (filters.maxArea) {
      const maxArea = parseFloat(filters.maxArea);
      filteredFields = filteredFields.filter(f => f.area <= maxArea);
    }

    if (filteredFields.length === 0) {
      toast.warning('未找到符合条件的地块');
      setStatistics(null);
      return;
    }

    // 计算统计结果
    const totalCount = filteredFields.length;
    const totalArea = filteredFields.reduce((sum, f) => sum + f.area, 0);
    const avgArea = totalArea / totalCount;
    const maxArea = Math.max(...filteredFields.map(f => f.area));
    const minArea = Math.min(...filteredFields.map(f => f.area));

    // 土壤类型分布
    const soilTypeMap = new Map<string, { count: number; area: number }>();
    filteredFields.forEach(f => {
      const current = soilTypeMap.get(f.soilType) || { count: 0, area: 0 };
      soilTypeMap.set(f.soilType, {
        count: current.count + 1,
        area: current.area + f.area,
      });
    });

    const soilTypeDistribution = Array.from(soilTypeMap.entries()).map(([key, value]) => {
      const soilType = soilTypes.find(s => s.key === key);
      return {
        name: soilType?.name || key,
        count: value.count,
        area: value.area,
        color: soilType?.color || '#6b7280',
      };
    });

    // 种植模式分布
    const plantingModeMap = new Map<string, { count: number; area: number }>();
    filteredFields.forEach(f => {
      const current = plantingModeMap.get(f.plantingMode) || { count: 0, area: 0 };
      plantingModeMap.set(f.plantingMode, {
        count: current.count + 1,
        area: current.area + f.area,
      });
    });

    const plantingModeDistribution = Array.from(plantingModeMap.entries()).map(([key, value]) => {
      const mode = plantingModes.find(m => m.key === key);
      return {
        name: mode?.name || key,
        count: value.count,
        area: value.area,
        emoji: mode?.emoji || '📍',
      };
    });

    // 标签分布
    const tagMap = new Map<string, number>();
    filteredFields.forEach(f => {
      f.tags.forEach(tag => {
        tagMap.set(tag, (tagMap.get(tag) || 0) + 1);
      });
    });

    const tagDistribution = Array.from(tagMap.entries()).map(([name, count]) => {
      const tag = tags.find(t => t.name === name);
      return {
        name,
        count,
        color: tag?.color || '#6b7280',
      };
    }).sort((a, b) => b.count - a.count);

    setStatistics({
      totalCount,
      totalArea,
      avgArea,
      maxArea,
      minArea,
      soilTypeDistribution,
      plantingModeDistribution,
      tagDistribution,
    });

    toast.success(`查询完成，找到 ${totalCount} 个地块`);
  };

  const exportData = () => {
    if (!statistics) {
      toast.error('请先执行查询');
      return;
    }

    const data = {
      查询时间: new Date().toLocaleString('zh-CN'),
      筛选条件: filters,
      统计结果: statistics,
    };

    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `地块统计分析_${new Date().getTime()}.json`;
    a.click();
    URL.revokeObjectURL(url);
    toast.success('数据导出成功');
  };

  const getSoilTypeName = (key: string) => {
    return soilTypes.find(s => s.key === key)?.name || key;
  };

  const getPlantingModeName = (key: string) => {
    return plantingModes.find(m => m.key === key)?.name || key;
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-green-800">统计分析</h2>
        <p className="text-muted-foreground">灵活的地块筛选和统计查询功能</p>
      </div>

      {/* 筛选条件 */}
      <Card className="p-6">
        <div className="flex items-center gap-2 mb-4">
          <Filter className="w-5 h-5 text-green-600" />
          <h3>筛选条件</h3>
        </div>

        <div className="space-y-6">
          {/* 关键词搜索 */}
          <div className="space-y-2">
            <Label>关键词搜索</Label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                placeholder="搜索地块名称、编号或位置..."
                value={filters.keyword}
                onChange={(e) => handleFilterChange('keyword', e.target.value)}
                className="pl-10"
              />
            </div>
          </div>

          {/* 土壤类型 */}
          <div className="space-y-2">
            <Label>土壤类型</Label>
            <div className="flex flex-wrap gap-2">
              {soilTypes.map((type) => (
                <Badge
                  key={type.id}
                  variant={filters.soilTypes.includes(type.key) ? 'default' : 'outline'}
                  className="cursor-pointer"
                  style={{
                    backgroundColor: filters.soilTypes.includes(type.key) ? type.color : 'transparent',
                    borderColor: type.color,
                    color: filters.soilTypes.includes(type.key) ? 'white' : type.color,
                  }}
                  onClick={() => toggleArrayFilter('soilTypes', type.key)}
                >
                  <div
                    className="w-2 h-2 rounded-full mr-2"
                    style={{ backgroundColor: type.color }}
                  />
                  {type.name}
                </Badge>
              ))}
            </div>
          </div>

          {/* 种植模式 */}
          <div className="space-y-2">
            <Label>种植模式</Label>
            <div className="flex flex-wrap gap-2">
              {plantingModes.map((mode) => (
                <Badge
                  key={mode.id}
                  variant={filters.plantingModes.includes(mode.key) ? 'default' : 'outline'}
                  className="cursor-pointer bg-green-600 hover:bg-green-700"
                  style={{
                    backgroundColor: filters.plantingModes.includes(mode.key) ? '#16a34a' : 'transparent',
                    borderColor: '#16a34a',
                    color: filters.plantingModes.includes(mode.key) ? 'white' : '#16a34a',
                  }}
                  onClick={() => toggleArrayFilter('plantingModes', mode.key)}
                >
                  <span className="mr-1">{mode.emoji}</span>
                  {mode.name}
                </Badge>
              ))}
            </div>
          </div>

          {/* 标签 */}
          <div className="space-y-2">
            <Label>标签</Label>
            <div className="flex flex-wrap gap-2">
              {tags.map((tag) => (
                <Badge
                  key={tag.id}
                  variant={filters.tags.includes(tag.name) ? 'default' : 'outline'}
                  className="cursor-pointer"
                  style={{
                    backgroundColor: filters.tags.includes(tag.name) ? tag.color : 'transparent',
                    borderColor: tag.color,
                    color: filters.tags.includes(tag.name) ? 'white' : tag.color,
                  }}
                  onClick={() => toggleArrayFilter('tags', tag.name)}
                >
                  {tag.name}
                </Badge>
              ))}
            </div>
          </div>

          {/* 面积范围 */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>最小面积（亩）</Label>
              <Input
                type="number"
                placeholder="如：50"
                value={filters.minArea}
                onChange={(e) => handleFilterChange('minArea', e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>最大面积（亩）</Label>
              <Input
                type="number"
                placeholder="如：200"
                value={filters.maxArea}
                onChange={(e) => handleFilterChange('maxArea', e.target.value)}
              />
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="flex gap-2 pt-4">
            <Button
              className="bg-green-600 hover:bg-green-700 flex-1"
              onClick={executeQuery}
            >
              <Search className="w-4 h-4 mr-2" />
              执行查询
            </Button>
            <Button
              variant="outline"
              onClick={clearFilters}
            >
              <Trash2 className="w-4 h-4 mr-2" />
              清空条件
            </Button>
          </div>
        </div>
      </Card>

      {/* 统计结果 */}
      {statistics && (
        <>
          {/* 基础统计 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-2">
                <BarChart3 className="w-5 h-5 text-green-600" />
                <h3>统计结果</h3>
              </div>
              <Button variant="outline" onClick={exportData}>
                <Download className="w-4 h-4 mr-2" />
                导出数据
              </Button>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
              <Card className="p-4 bg-green-50">
                <div className="text-sm text-muted-foreground mb-1">地块总数</div>
                <div className="text-2xl text-green-600">{statistics.totalCount}</div>
              </Card>
              <Card className="p-4 bg-blue-50">
                <div className="text-sm text-muted-foreground mb-1">总面积</div>
                <div className="text-2xl text-blue-600">{statistics.totalArea.toFixed(2)} 亩</div>
              </Card>
              <Card className="p-4 bg-purple-50">
                <div className="text-sm text-muted-foreground mb-1">平均面积</div>
                <div className="text-2xl text-purple-600">{statistics.avgArea.toFixed(2)} 亩</div>
              </Card>
              <Card className="p-4 bg-orange-50">
                <div className="text-sm text-muted-foreground mb-1">最大面积</div>
                <div className="text-2xl text-orange-600">{statistics.maxArea.toFixed(2)} 亩</div>
              </Card>
              <Card className="p-4 bg-pink-50">
                <div className="text-sm text-muted-foreground mb-1">最小面积</div>
                <div className="text-2xl text-pink-600">{statistics.minArea.toFixed(2)} 亩</div>
              </Card>
            </div>
          </Card>

          {/* 图表选择 */}
          <div className="flex items-center gap-2">
            <Button
              variant={chartType === 'bar' ? 'default' : 'outline'}
              onClick={() => setChartType('bar')}
              className={chartType === 'bar' ? 'bg-green-600 hover:bg-green-700' : ''}
            >
              <BarChart className="w-4 h-4 mr-2" />
              柱状图
            </Button>
            <Button
              variant={chartType === 'pie' ? 'default' : 'outline'}
              onClick={() => setChartType('pie')}
              className={chartType === 'pie' ? 'bg-green-600 hover:bg-green-700' : ''}
            >
              <PieChart className="w-4 h-4 mr-2" />
              饼图
            </Button>
          </div>

          {/* 土壤类型分布 */}
          <Card className="p-6">
            <h3 className="mb-4">土壤类型分布</h3>
            {chartType === 'bar' ? (
              <ResponsiveContainer width="100%" height={300}>
                <RechartsBarChart data={statistics.soilTypeDistribution}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Bar dataKey="count" name="地块数量" fill="#22c55e" />
                  <Bar dataKey="area" name="总面积（亩）" fill="#3b82f6" />
                </RechartsBarChart>
              </ResponsiveContainer>
            ) : (
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground mb-2 text-center">按地块数量</p>
                  <ResponsiveContainer width="100%" height={250}>
                    <RechartsPieChart>
                      <Pie
                        data={statistics.soilTypeDistribution}
                        dataKey="count"
                        nameKey="name"
                        cx="50%"
                        cy="50%"
                        outerRadius={80}
                        label
                      >
                        {statistics.soilTypeDistribution.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={entry.color} />
                        ))}
                      </Pie>
                      <Tooltip />
                      <Legend />
                    </RechartsPieChart>
                  </ResponsiveContainer>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground mb-2 text-center">按面积</p>
                  <ResponsiveContainer width="100%" height={250}>
                    <RechartsPieChart>
                      <Pie
                        data={statistics.soilTypeDistribution}
                        dataKey="area"
                        nameKey="name"
                        cx="50%"
                        cy="50%"
                        outerRadius={80}
                        label
                      >
                        {statistics.soilTypeDistribution.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={entry.color} />
                        ))}
                      </Pie>
                      <Tooltip />
                      <Legend />
                    </RechartsPieChart>
                  </ResponsiveContainer>
                </div>
              </div>
            )}
          </Card>

          {/* 种植模式分布 */}
          <Card className="p-6">
            <h3 className="mb-4">种植模式分布</h3>
            {chartType === 'bar' ? (
              <ResponsiveContainer width="100%" height={300}>
                <RechartsBarChart data={statistics.plantingModeDistribution}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Bar dataKey="count" name="地块数量" fill="#a855f7" />
                  <Bar dataKey="area" name="总面积（亩）" fill="#f59e0b" />
                </RechartsBarChart>
              </ResponsiveContainer>
            ) : (
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-muted-foreground mb-2 text-center">按地块数量</p>
                  <ResponsiveContainer width="100%" height={250}>
                    <RechartsPieChart>
                      <Pie
                        data={statistics.plantingModeDistribution}
                        dataKey="count"
                        nameKey="name"
                        cx="50%"
                        cy="50%"
                        outerRadius={80}
                        label
                      >
                        {statistics.plantingModeDistribution.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip />
                      <Legend />
                    </RechartsPieChart>
                  </ResponsiveContainer>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground mb-2 text-center">按面积</p>
                  <ResponsiveContainer width="100%" height={250}>
                    <RechartsPieChart>
                      <Pie
                        data={statistics.plantingModeDistribution}
                        dataKey="area"
                        nameKey="name"
                        cx="50%"
                        cy="50%"
                        outerRadius={80}
                        label
                      >
                        {statistics.plantingModeDistribution.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip />
                      <Legend />
                    </RechartsPieChart>
                  </ResponsiveContainer>
                </div>
              </div>
            )}
          </Card>

          {/* 标签分布 */}
          {statistics.tagDistribution.length > 0 && (
            <Card className="p-6">
              <h3 className="mb-4">标签分布</h3>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                {statistics.tagDistribution.map((tag) => (
                  <Card key={tag.name} className="p-4">
                    <Badge
                      style={{ backgroundColor: tag.color, color: 'white' }}
                      className="w-full justify-center mb-2"
                    >
                      {tag.name}
                    </Badge>
                    <div className="text-center">
                      <div className="text-2xl text-green-600">{tag.count}</div>
                      <div className="text-xs text-muted-foreground">个地块</div>
                    </div>
                  </Card>
                ))}
              </div>
            </Card>
          )}
        </>
      )}

      {/* 使用示例 */}
      <Card className="p-6 bg-blue-50 border-blue-200">
        <h3 className="mb-2">💡 使用示例</h3>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 统计所有沙土且面积大于50亩的地块：选择"沙土"，设置最小面积为50</li>
          <li>• 统计有机种植的露地地块：选择"露地"种植模式，选择"有机种植"标签</li>
          <li>• 统计50-100亩的大棚地块：选择"大棚"，设置面积范围50-100</li>
          <li>• 多条件组合：可同时选择多个土壤类型、种植模式和标签</li>
        </ul>
      </Card>
    </div>
  );
}
