'use client';

import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { SpatialQueryState, SpatialQueryAction } from './spatialQueryReducer';
import {
  MapPin,
  Shapes,
  Circle,
  Search,
  Map,
  RefreshCw,
  Download,
  Code,
  Database
} from 'lucide-react';

interface QueryPanelProps {
  state: SpatialQueryState;
  dispatch: React.Dispatch<SpatialQueryAction>;
  onExecuteQuery: () => void;
  onShowMapPicker: () => void;
}

export function QueryPanel({ state, dispatch, onExecuteQuery, onShowMapPicker }: QueryPanelProps) {
  return (
    <div className="space-y-6">
      {/* 查询类型选择 */}
      <Card className="p-6 bg-card">
        <div className="space-y-4">
          <div className="flex items-center gap-2">
            <Search className="w-5 h-5 text-blue-600 dark:text-blue-400" />
            <h3 className="text-lg font-semibold">空间查询类型</h3>
          </div>

          <Select
            value={state.queryType}
            onValueChange={(value: any) => dispatch({ type: 'SET_QUERY_TYPE', payload: value })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="point-in-polygon">
                <div className="flex items-center gap-2">
                  <MapPin className="w-4 h-4" />
                  <span>点在多边形内查询</span>
                </div>
              </SelectItem>
              <SelectItem value="polygon-intersect">
                <div className="flex items-center gap-2">
                  <Shapes className="w-4 h-4" />
                  <span>多边形相交查询</span>
                </div>
              </SelectItem>
              <SelectItem value="polygon-adjacent">
                <div className="flex items-center gap-2">
                  <Map className="w-4 h-4" />
                  <span>多边形相邻查询</span>
                </div>
              </SelectItem>
              <SelectItem value="buffer">
                <div className="flex items-center gap-2">
                  <Circle className="w-4 h-4" />
                  <span>缓冲区查询</span>
                </div>
              </SelectItem>
            </SelectContent>
          </Select>

          <div className="p-4 bg-muted/50 rounded-lg">
            <p className="text-sm text-muted-foreground">
              {state.queryType === 'point-in-polygon' && '查询指定坐标点位于哪些地块范围内'}
              {state.queryType === 'polygon-intersect' && '查询与指定多边形相交的所有地块'}
              {state.queryType === 'polygon-adjacent' && '查询与指定多边形相邻（共享边界）的地块'}
              {state.queryType === 'buffer' && '查询指定点周围一定距离范围内的地块'}
            </p>
          </div>
        </div>
      </Card>

      {/* 查询参数设置 */}
      <Card className="p-6 bg-card">
        <div className="space-y-4">
          <h4 className="font-medium">查询参数</h4>

          {state.queryType === 'point-in-polygon' && (
            <div className="space-y-3">
              <Label>查询点坐标</Label>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label className="text-sm text-muted-foreground">纬度</Label>
                  <Input
                    type="number"
                    step="0.000001"
                    placeholder="39.9042"
                    value={state.selectedPoint?.lat || ''}
                    onChange={(e) => dispatch({
                      type: 'SET_SELECTED_POINT',
                      payload: state.selectedPoint
                        ? { ...state.selectedPoint, lat: parseFloat(e.target.value) || 0 }
                        : { lat: parseFloat(e.target.value) || 0, lng: 0 }
                    })}
                  />
                </div>
                <div>
                  <Label className="text-sm text-muted-foreground">经度</Label>
                  <Input
                    type="number"
                    step="0.000001"
                    placeholder="116.4074"
                    value={state.selectedPoint?.lng || ''}
                    onChange={(e) => dispatch({
                      type: 'SET_SELECTED_POINT',
                      payload: state.selectedPoint
                        ? { ...state.selectedPoint, lng: parseFloat(e.target.value) || 0 }
                        : { lat: 0, lng: parseFloat(e.target.value) || 0 }
                    })}
                  />
                </div>
              </div>
              <Button
                variant="outline"
                className="w-full"
                onClick={() => {
                  dispatch({ type: 'SET_SHOW_MAP_PICKER', payload: true });
                  dispatch({ type: 'SET_MAP_PICKER_MODE', payload: 'point' });
                  onShowMapPicker();
                }}
              >
                <Map className="w-4 h-4 mr-2" />
                在地图上选择点
              </Button>
            </div>
          )}

          {(state.queryType === 'polygon-intersect' || state.queryType === 'polygon-adjacent') && (
            <div className="space-y-3">
              <Label>查询多边形</Label>
              {state.queryPolygon && state.queryPolygon.length > 0 ? (
                <div className="p-3 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-medium text-green-800 dark:text-green-200">
                      已选择多边形 ({state.queryPolygon.length} 个顶点)
                    </span>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => dispatch({ type: 'SET_QUERY_POLYGON', payload: null })}
                    >
                      <RefreshCw className="w-3 h-3" />
                    </Button>
                  </div>
                  <div className="text-xs text-green-700 dark:text-green-300">
                    顶点坐标已保存，可在地图上预览
                  </div>
                </div>
              ) : (
                <Button
                  variant="outline"
                  className="w-full"
                  onClick={() => {
                    dispatch({ type: 'SET_SHOW_MAP_PICKER', payload: true });
                    dispatch({ type: 'SET_MAP_PICKER_MODE', payload: 'polygon' });
                    onShowMapPicker();
                  }}
                >
                  <Shapes className="w-4 h-4 mr-2" />
                  在地图上绘制多边形
                </Button>
              )}
            </div>
          )}

          {state.queryType === 'buffer' && (
            <div className="space-y-3">
              <div>
                <Label>缓冲区中心点</Label>
                <div className="grid grid-cols-2 gap-3 mt-2">
                  <div>
                    <Label className="text-sm text-muted-foreground">纬度</Label>
                    <Input
                      type="number"
                      step="0.000001"
                      placeholder="39.9042"
                      value={state.selectedPoint?.lat || ''}
                      onChange={(e) => dispatch({
                        type: 'SET_SELECTED_POINT',
                        payload: state.selectedPoint
                          ? { ...state.selectedPoint, lat: parseFloat(e.target.value) || 0 }
                          : { lat: parseFloat(e.target.value) || 0, lng: 0 }
                      })}
                    />
                  </div>
                  <div>
                    <Label className="text-sm text-muted-foreground">经度</Label>
                    <Input
                      type="number"
                      step="0.000001"
                      placeholder="116.4074"
                      value={state.selectedPoint?.lng || ''}
                      onChange={(e) => dispatch({
                        type: 'SET_SELECTED_POINT',
                        payload: state.selectedPoint
                          ? { ...state.selectedPoint, lng: parseFloat(e.target.value) || 0 }
                          : { lat: 0, lng: parseFloat(e.target.value) || 0 }
                      })}
                    />
                  </div>
                </div>
              </div>

              <div>
                <Label>缓冲区半径（米）</Label>
                <Input
                  type="number"
                  min="10"
                  max="10000"
                  step="10"
                  value={state.bufferDistance}
                  onChange={(e) => dispatch({
                    type: 'SET_BUFFER_DISTANCE',
                    payload: parseInt(e.target.value) || 100
                  })}
                />
              </div>

              <Button
                variant="outline"
                className="w-full"
                onClick={() => {
                  dispatch({ type: 'SET_SHOW_MAP_PICKER', payload: true });
                  dispatch({ type: 'SET_MAP_PICKER_MODE', payload: 'point' });
                  onShowMapPicker();
                }}
              >
                <Map className="w-4 h-4 mr-2" />
                在地图上选择中心点
              </Button>
            </div>
          )}

          <Separator />

          <Button
            className="w-full bg-blue-600 hover:bg-blue-700"
            onClick={onExecuteQuery}
            disabled={state.isQuerying || !isQueryValid(state)}
          >
            {state.isQuerying ? (
              <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
            ) : (
              <Search className="w-4 h-4 mr-2" />
            )}
            执行查询
          </Button>
        </div>
      </Card>

      {/* 导出选项 */}
      {state.queryResult && state.queryResult.length > 0 && (
        <Card className="p-6 bg-card">
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Download className="w-5 h-5 text-green-600 dark:text-green-400" />
              <h3 className="text-lg font-semibold">导出查询结果</h3>
            </div>

            <div className="space-y-3">
              <Label>导出格式</Label>
              <Select
                value={state.exportFormat}
                onValueChange={(value: any) => dispatch({ type: 'SET_EXPORT_FORMAT', payload: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="geojson">GeoJSON</SelectItem>
                  <SelectItem value="kml">KML</SelectItem>
                  <SelectItem value="csv">CSV</SelectItem>
                </SelectContent>
              </Select>

              <Button
                className="w-full bg-green-600 hover:bg-green-700"
                onClick={() => dispatch({ type: 'SET_SHOW_EXPORT_DIALOG', payload: true })}
              >
                <Download className="w-4 h-4 mr-2" />
                导出数据
              </Button>
            </div>
          </div>
        </Card>
      )}

      {/* SQL示例 */}
      {state.queryResult && (
        <Card className="p-6 bg-card">
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Code className="w-5 h-5 text-purple-600 dark:text-purple-400" />
              <h3 className="text-lg font-semibold">PostGIS SQL示例</h3>
            </div>

            <div className="space-y-3">
              <Label>SQL查询语句</Label>
              <Textarea
                value={generateSQLExample(state)}
                readOnly
                className="font-mono text-sm bg-muted"
                rows={6}
              />
              <Button
                variant="outline"
                className="w-full"
                onClick={() => {
                  navigator.clipboard.writeText(generateSQLExample(state));
                  // 这里可以添加toast提示
                }}
              >
                <Database className="w-4 h-4 mr-2" />
                复制SQL语句
              </Button>
            </div>
          </div>
        </Card>
      )}
    </div>
  );
}

// 检查查询参数是否有效
function isQueryValid(state: SpatialQueryState): boolean {
  switch (state.queryType) {
    case 'point-in-polygon':
      return state.selectedPoint !== null;
    case 'polygon-intersect':
    case 'polygon-adjacent':
      return state.queryPolygon !== null && state.queryPolygon.length >= 3;
    case 'buffer':
      return state.selectedPoint !== null && state.bufferDistance > 0;
    default:
      return false;
  }
}

// 生成SQL示例的简化版本
function generateSQLExample(state: SpatialQueryState): string {
  switch (state.queryType) {
    case 'point-in-polygon':
      return `-- 点在多边形内查询
SELECT * FROM fields
WHERE ST_Contains(
  geometry,
  ST_GeomFromText('POINT(${state.selectedPoint?.lng} ${state.selectedPoint?.lat})', 4326)
);`;

    case 'polygon-intersect':
      return `-- 多边形相交查询
SELECT * FROM fields
WHERE ST_Intersects(
  geometry,
  ST_GeomFromText('POLYGON((...))', 4326)
);`;

    case 'polygon-adjacent':
      return `-- 多边形相邻查询
SELECT * FROM fields
WHERE ST_Touches(
  geometry,
  ST_GeomFromText('POLYGON((...))', 4326)
);`;

    case 'buffer':
      return `-- 缓冲区查询
SELECT * FROM fields
WHERE ST_DWithin(
  geometry,
  ST_GeomFromText('POINT(${state.selectedPoint?.lng} ${state.selectedPoint?.lat})', 4326),
  ${state.bufferDistance}
);`;

    default:
      return '-- 请选择查询类型';
  }
}