'use client';

import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Download, FileText, Plus, MapPin, Layers, BarChart3, Droplets } from 'lucide-react';
import { SoilDataState, SoilDataAction } from './soilDataReducer';
import StatisticsCards from './StatisticsCards';
import SamplePointsList from './SamplePointsList';
import SpatialDistribution from './SpatialDistribution';
import ProfileInformation from './ProfileInformation';
import StatisticalAnalysis from './StatisticalAnalysis';
import AddSamplePointDialog from './AddSamplePointDialog';
import EditSamplePointDialog from './EditSamplePointDialog';
import LayerDataDialog from './LayerDataDialog';
import DeleteConfirmDialog from './DeleteConfirmDialog';
import UsageGuide from './UsageGuide';

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

export default function SoilDataContent({ state, dispatch }: SoilDataContentProps) {
  const handleExportData = () => {
    // 生成CSV数据
    const headers = ['采样点编号', '地块', '纬度', '经度', '采样日期', '采样人', '深度', 'pH值', '有机质(g/kg)', '全氮(g/kg)', '有效磷(mg/kg)', '速效钾(mg/kg)', '含水量(%)'];
    const rows = state.samplePoints.flatMap(point =>
      point.layers.map(layer => [
        point.code,
        point.fieldName,
        point.latitude,
        point.longitude,
        point.sampleDate,
        point.sampler,
        layer.depth,
        layer.pH,
        layer.organicMatter,
        layer.nitrogen,
        layer.phosphorus,
        layer.potassium,
        layer.moisture,
      ])
    );

    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.join(',')),
    ].join('\n');

    // 创建下载链接
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `土壤基础数据_${new Date().toLocaleDateString()}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const handleGenerateReport = () => {
    // 生成报告HTML内容
    const reportHTML = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>土壤检测报告</title>
  <style>
    body { font-family: Arial, sans-serif; padding: 40px; }
    h1 { color: #2d5016; border-bottom: 3px solid #4ade80; padding-bottom: 10px; }
    h2 { color: #16a34a; margin-top: 30px; }
    table { width: 100%; border-collapse: collapse; margin: 20px 0; }
    th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
    th { background-color: #f0fdf4; color: #166534; }
    tr:nth-child(even) { background-color: #f9fafb; }
    .summary { background: #f0fdf4; padding: 20px; border-radius: 8px; margin: 20px 0; }
    .footer { margin-top: 40px; text-align: center; color: #666; font-size: 12px; }
  </style>
</head>
<body>
  <h1>土壤基础数据检测报告</h1>
  <div class="summary">
    <h3>报告概要</h3>
    <p><strong>生成日期：</strong>${new Date().toLocaleDateString()}</p>
    <p><strong>采样点总数：</strong>${state.samplePoints.length} 个</p>
    <p><strong>覆盖地块：</strong>${state.statistics?.totalFields || 0} 个</p>
    <p><strong>分层样本：</strong>${state.statistics?.totalLayers || 0} 层</p>
  </div>

  <h2>采样点详细数据</h2>
  ${state.samplePoints.map(point => `
    <h3>${point.code} - ${point.fieldName}</h3>
    <p><strong>坐标：</strong>${point.latitude.toFixed(6)}, ${point.longitude.toFixed(6)}</p>
    <p><strong>采样日期：</strong>${point.sampleDate} | <strong>采样人：</strong>${point.sampler}</p>
    <table>
      <thead>
        <tr>
          <th>深度</th>
          <th>pH值</th>
          <th>有机质(g/kg)</th>
          <th>全氮(g/kg)</th>
          <th>有效磷(mg/kg)</th>
          <th>速效钾(mg/kg)</th>
          <th>含水量(%)</th>
        </tr>
      </thead>
      <tbody>
        ${point.layers.map(layer => `
          <tr>
            <td>${layer.depth}</td>
            <td>${layer.pH}</td>
            <td>${layer.organicMatter}</td>
            <td>${layer.nitrogen}</td>
            <td>${layer.phosphorus}</td>
            <td>${layer.potassium}</td>
            <td>${layer.moisture}</td>
          </tr>
        `).join('')}
      </tbody>
    </table>
  `).join('')}

  <div class="footer">
    <p>本报告由智慧农业生产管理系统自动生成</p>
    <p>报告生成时间：${new Date().toLocaleString()}</p>
  </div>
</body>
</html>
    `;

    // 创建下载链接
    const blob = new Blob([reportHTML], { type: 'text/html;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `土壤检测报告_${new Date().toLocaleDateString()}.html`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="space-y-6">
      {/* 操作按钮区域 */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold text-green-800 dark:text-green-200">
            土壤采样点数据管理
          </h3>
          <p className="text-sm text-muted-foreground">
            管理土壤采样点、记录分层数据、分析土壤理化性状
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleExportData}>
            <Download className="w-4 h-4 mr-2" />
            导出数据
          </Button>
          <Button variant="outline" onClick={handleGenerateReport}>
            <FileText className="w-4 h-4 mr-2" />
            生成报告
          </Button>
          <Button
            className="bg-green-600 hover:bg-green-700"
            onClick={() => dispatch({ type: 'SET_SHOW_ADD_DIALOG', payload: true })}
          >
            <Plus className="w-4 h-4 mr-2" />
            新增采样点
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <StatisticsCards statistics={state.statistics} />

      {/* 主要内容区域 */}
      <Tabs value={state.activeTab} onValueChange={(value) => dispatch({ type: 'SET_ACTIVE_TAB', payload: value })}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="list">采样点列表</TabsTrigger>
          <TabsTrigger value="distribution">空间分布</TabsTrigger>
          <TabsTrigger value="profile">剖面信息</TabsTrigger>
          <TabsTrigger value="statistics">统计分析</TabsTrigger>
        </TabsList>

        <TabsContent value="list" className="space-y-4">
          <SamplePointsList state={state} dispatch={dispatch} />
        </TabsContent>

        <TabsContent value="distribution" className="space-y-4">
          <SpatialDistribution samplePoints={state.samplePoints} />
        </TabsContent>

        <TabsContent value="profile" className="space-y-4">
          <ProfileInformation samplePoints={state.samplePoints} />
        </TabsContent>

        <TabsContent value="statistics" className="space-y-4">
          <StatisticalAnalysis statistics={state.statistics} />
        </TabsContent>
      </Tabs>

      {/* 对话框组件 */}
      <AddSamplePointDialog state={state} dispatch={dispatch} />
      <EditSamplePointDialog state={state} dispatch={dispatch} />
      <LayerDataDialog state={state} dispatch={dispatch} />
      <DeleteConfirmDialog state={state} dispatch={dispatch} />

      {/* 使用说明 */}
      <UsageGuide />
    </div>
  );
}