'use client';

import { useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog';
import { ExternalDataState, ExternalDataAction } from './externalDataReducer';
import { DataSourceForm, DataSourceType, AccessMethod, accessMethods } from '../types';
import { Database, Plus, Upload, Code, Wifi } from 'lucide-react';
import { toast } from 'sonner';

interface AddDataSourceDialogProps {
  state: ExternalDataState;
  dispatch: React.Dispatch<ExternalDataAction>;
}

export function AddDataSourceDialog({ state, dispatch }: AddDataSourceDialogProps) {
  const [formData, setFormData] = useState<DataSourceForm>({
    name: '',
    type: '气象数据',
    provider: '',
    accessMethod: 'API对接',
    apiEndpoint: '',
    updateFrequency: '',
    description: '',
  });

  const resetForm = () => {
    setFormData({
      name: '',
      type: '气象数据',
      provider: '',
      accessMethod: 'API对接',
      apiEndpoint: '',
      updateFrequency: '',
      description: '',
    });
  };

  const handleSubmit = () => {
    if (!formData.name || !formData.provider || !formData.updateFrequency) {
      toast.error('请填写必要字段');
      return;
    }

    const newDataSource = {
      id: `ext-${Date.now()}`,
      ...formData,
      lastUpdateTime: new Date().toLocaleString('zh-CN'),
      dataPoints: 0,
      status: '待配置' as const,
      dataFields: [],
    };

    dispatch({ type: 'ADD_DATA_SOURCE', payload: newDataSource });
    dispatch({ type: 'SHOW_ADD_DIALOG', payload: false });
    resetForm();
    toast.success('数据源添加成功');
  };

  const handleClose = () => {
    dispatch({ type: 'SHOW_ADD_DIALOG', payload: false });
    resetForm();
  };

  const getAccessMethodIcon = (method: AccessMethod) => {
    switch (method) {
      case 'API对接':
        return <Code className="w-4 h-4" />;
      case 'FTP传输':
        return <Upload className="w-4 h-4" />;
      case 'WebSocket':
        return <Wifi className="w-4 h-4" />;
      case '手动上传':
        return <Upload className="w-4 h-4" />;
      default:
        return <Database className="w-4 h-4" />;
    }
  };

  return (
    <Dialog open={state.showAddDialog} onOpenChange={handleClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Plus className="w-5 h-5" />
            添加数据源
          </DialogTitle>
          <DialogDescription>
            配置新的外部数据源，支持多种接入方式
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* 基本信息 */}
          <Card className="p-4 bg-muted/20">
            <h3 className="font-medium mb-4">基本信息</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="name">数据源名称 *</Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="例如：国家气象局API"
                />
              </div>
              <div>
                <Label htmlFor="provider">数据提供商 *</Label>
                <Input
                  id="provider"
                  value={formData.provider}
                  onChange={(e) => setFormData({ ...formData, provider: e.target.value })}
                  placeholder="例如：中国气象局"
                />
              </div>
            </div>
          </Card>

          {/* 数据配置 */}
          <Card className="p-4 bg-muted/20">
            <h3 className="font-medium mb-4">数据配置</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="type">数据类型</Label>
                <Select
                  value={formData.type}
                  onValueChange={(value: DataSourceType) =>
                    setFormData({ ...formData, type: value })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="气象数据">气象数据</SelectItem>
                    <SelectItem value="卫星遥感">卫星遥感</SelectItem>
                    <SelectItem value="土壤数据">土壤数据</SelectItem>
                    <SelectItem value="作物生长">作物生长</SelectItem>
                    <SelectItem value="其他">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="updateFrequency">更新频率 *</Label>
                <Input
                  id="updateFrequency"
                  value={formData.updateFrequency}
                  onChange={(e) => setFormData({ ...formData, updateFrequency: e.target.value })}
                  placeholder="例如：每小时、每5天"
                />
              </div>
            </div>
          </Card>

          {/* 接入方式 */}
          <Card className="p-4 bg-muted/20">
            <h3 className="font-medium mb-4">接入方式</h3>
            <div className="space-y-4">
              <div>
                <Label>选择接入方式</Label>
                <div className="grid grid-cols-2 gap-3 mt-2">
                  {accessMethods.map((method) => (
                    <Button
                      key={method}
                      type="button"
                      variant={formData.accessMethod === method ? 'default' : 'outline'}
                      className="justify-start h-auto p-3"
                      onClick={() => setFormData({ ...formData, accessMethod: method })}
                    >
                      <div className="flex items-center gap-2">
                        {getAccessMethodIcon(method)}
                        <div className="text-left">
                          <div className="font-medium text-sm">{method}</div>
                        </div>
                      </div>
                    </Button>
                  ))}
                </div>
              </div>

              {formData.accessMethod === 'API对接' && (
                <div>
                  <Label htmlFor="apiEndpoint">API端点</Label>
                  <Input
                    id="apiEndpoint"
                    value={formData.apiEndpoint}
                    onChange={(e) => setFormData({ ...formData, apiEndpoint: e.target.value })}
                    placeholder="https://api.example.com/v1/data"
                  />
                </div>
              )}
            </div>
          </Card>

          {/* 描述 */}
          <Card className="p-4 bg-muted/20">
            <Label htmlFor="description">描述</Label>
            <Textarea
              id="description"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              placeholder="描述数据源的用途、数据内容等信息..."
              rows={3}
            />
          </Card>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleClose}>
            取消
          </Button>
          <Button onClick={handleSubmit}>
            <Plus className="w-4 h-4 mr-2" />
            添加数据源
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}