'use client';

import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Search, MapPin, Layers, Edit, Trash2, Leaf, Zap, TrendingUp, Droplets } from 'lucide-react';
import { SoilDataState, SoilDataAction, getPHLevel } from './soilDataReducer';

interface SamplePointsListProps {
  state: SoilDataState;
  dispatch: React.Dispatch<SoilDataAction>;
}

export default function SamplePointsList({ state, dispatch }: SamplePointsListProps) {
  const handleViewLayers = (point: any) => {
    dispatch({ type: 'SET_SELECTED_POINT', payload: point });
    dispatch({ type: 'SET_SHOW_LAYER_DIALOG', payload: true });
  };

  const handleEditPoint = (point: any) => {
    dispatch({ type: 'SET_SELECTED_POINT', payload: point });
    dispatch({ type: 'SET_NEW_POINT', payload: point });
    dispatch({ type: 'SET_SHOW_EDIT_DIALOG', payload: true });
  };

  const handleDeleteClick = (pointId: string) => {
    dispatch({ type: 'SET_POINT_TO_DELETE', payload: pointId });
    dispatch({ type: 'SET_SHOW_DELETE_DIALOG', payload: true });
  };

  const handleSearchChange = (value: string) => {
    dispatch({ type: 'SET_FILTERS', payload: { searchKeyword: value } });
  };

  const handleFieldChange = (value: string) => {
    dispatch({ type: 'SET_FILTERS', payload: { selectedField: value } });
  };

  // 筛选采样点
  const filteredPoints = state.samplePoints.filter(point => {
    const matchesSearch = !state.filters.searchKeyword ||
      point.code.toLowerCase().includes(state.filters.searchKeyword.toLowerCase()) ||
      point.fieldName.toLowerCase().includes(state.filters.searchKeyword.toLowerCase());

    const matchesField = state.filters.selectedField === 'all' ||
      point.fieldName === state.filters.selectedField;

    return matchesSearch && matchesField;
  });

  return (
    <div className="space-y-4">
      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="flex gap-4">
          <div className="flex-1">
            <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={state.filters.searchKeyword}
                onChange={(e) => handleSearchChange(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <Select value={state.filters.selectedField} onValueChange={handleFieldChange}>
            <SelectTrigger className="w-[200px]">
              <SelectValue placeholder="选择地块" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部地块</SelectItem>
              {Array.from(new Set(state.samplePoints.map(p => p.fieldName))).map(fieldName => (
                <SelectItem key={fieldName} value={fieldName}>
                  {fieldName}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 采样点列表 */}
      <div className="space-y-3">
        {filteredPoints.map((point) => (
          <Card key={point.id} className="p-4 bg-card hover:bg-muted/50 transition-colors">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <div className="flex items-center gap-3 mb-3">
                  <MapPin className="w-5 h-5 text-green-600" />
                  <div>
                    <div className="flex items-center gap-2">
                      <h4 className="font-semibold">{point.code}</h4>
                      <Badge variant="outline" className="font-light">{point.fieldName}</Badge>
                    </div>
                    <p className="text-sm text-muted-foreground mt-1">
                      坐标: {point.latitude.toFixed(6)}, {point.longitude.toFixed(6)}
                    </p>
                  </div>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 pl-8">
                  <div>
                    <span className="text-xs text-muted-foreground">采样日期</span>
                    <p className="text-sm mt-1">{point.sampleDate}</p>
                  </div>
                  <div>
                    <span className="text-xs text-muted-foreground">采样人</span>
                    <p className="text-sm mt-1">{point.sampler}</p>
                  </div>
                  <div>
                    <span className="text-xs text-muted-foreground">分层数</span>
                    <p className="text-sm mt-1">{point.layers.length} 层</p>
                  </div>
                  <div>
                    <span className="text-xs text-muted-foreground">表层pH值</span>
                    <div className="flex items-center gap-2 mt-1">
                      <span className="text-sm">{point.layers[0]?.pH}</span>
                      <div className={`w-2 h-2 rounded-full ${getPHLevel(point.layers[0]?.pH || 0).color}`} />
                    </div>
                  </div>
                </div>

                {/* 表层指标快览 */}
                {point.layers[0] && (
                  <div className="mt-3 p-3 bg-muted rounded-lg">
                    <div className="text-xs text-muted-foreground mb-2">表层指标（0-20cm）</div>
                    <div className="grid grid-cols-2 md:grid-cols-5 gap-3 text-sm">
                      <div className="flex items-center gap-2">
                        <Leaf className="w-4 h-4 text-green-600" />
                        <span>有机质: <strong>{point.layers[0].organicMatter}</strong> g/kg</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <Zap className="w-4 h-4 text-blue-600" />
                        <span>全氮: <strong>{point.layers[0].nitrogen}</strong> g/kg</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <TrendingUp className="w-4 h-4 text-orange-600" />
                        <span>有效磷: <strong>{point.layers[0].phosphorus}</strong> mg/kg</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <TrendingUp className="w-4 h-4 text-purple-600" />
                        <span>速效钾: <strong>{point.layers[0].potassium}</strong> mg/kg</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <Droplets className="w-4 h-4 text-cyan-600" />
                        <span>含水量: <strong>{point.layers[0].moisture}</strong>%</span>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <div className="flex gap-2">
                <Button variant="outline" size="sm" onClick={() => handleViewLayers(point)}>
                  <Layers className="w-4 h-4 mr-1" />
                  查看剖面
                </Button>
                <Button variant="outline" size="sm" onClick={() => handleEditPoint(point)}>
                  <Edit className="w-4 h-4" />
                </Button>
                <Button variant="outline" size="sm" onClick={() => handleDeleteClick(point.id)}>
                  <Trash2 className="w-4 h-4 text-destructive" />
                </Button>
              </div>
            </div>
          </Card>
        ))}

        {filteredPoints.length === 0 && (
          <Card className="p-8 text-center">
            <div className="text-muted-foreground">
              <MapPin className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>暂无采样点数据</p>
              <p className="text-sm mt-1">点击"新增采样点"开始添加数据</p>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}