'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';
import Navbar from '@/components/Navbar';
import {
  Wheat, MapPin, FileText, Upload,
  Loader2, AlertTriangle,
  Mail, Clock, Shield, History,
} from 'lucide-react';

interface SummaryData {
  year: number;
  total_fields: number;
  assigned_fields: number;
  unassigned_fields: number;
  total_plans: number;
  total_area: number;
  by_crop: { crop: string; count: number; area: number }[];
}

interface MailStats {
  today_processed: number;
  today_notified: number;
  feedback_pending: number;
  total_rules: number;
}

export default function DashboardPage() {
  const router = useRouter();
  const currentYear = new Date().getFullYear();
  const [year, setYear] = useState(currentYear);
  const [summary, setSummary] = useState<SummaryData | null>(null);
  const [summaryLoading, setSummaryLoading] = useState(true);
  const [mailStats, setMailStats] = useState<MailStats | null>(null);
  const [mailLoading, setMailLoading] = useState(true);

  useEffect(() => {
    const fetchSummary = async () => {
      setSummaryLoading(true);
      try {
        const res = await api.get(`/plans/summary/?year=${year}`);
        setSummary(res.data);
      } catch (error) {
        console.error('Failed to fetch summary:', error);
      } finally {
        setSummaryLoading(false);
      }
    };
    fetchSummary();
  }, [year]);

  useEffect(() => {
    const fetchMailStats = async () => {
      setMailLoading(true);
      try {
        const res = await api.get('/mail/stats/');
        setMailStats(res.data);
      } catch (error) {
        console.error('Failed to fetch mail stats:', error);
      } finally {
        setMailLoading(false);
      }
    };
    fetchMailStats();
  }, []);

  const years = [];
  for (let y = currentYear + 1; y >= currentYear - 3; y--) {
    years.push(y);
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Navbar />
      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <h1 className="text-2xl font-bold text-gray-900 mb-6">ダッシュボード</h1>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">

          {/* ===== 作付け計画モジュール ===== */}
          <div className="bg-white rounded-lg shadow flex flex-col">
            <div className="px-5 py-4 border-b border-gray-200 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Wheat className="h-5 w-5 text-green-600" />
                <h2 className="text-base font-semibold text-gray-900">作付け計画</h2>
              </div>
              <select
                value={year}
                onChange={(e) => setYear(Number(e.target.value))}
                className="px-3 py-1.5 border border-gray-300 rounded-md text-sm"
              >
                {years.map((y) => (
                  <option key={y} value={y}>{y}年度</option>
                ))}
              </select>
            </div>

            <div className="p-5 space-y-4 flex-1">
              {summaryLoading ? (
                <div className="flex justify-center py-12">
                  <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
                </div>
              ) : summary ? (
                <>
                  {/* 集計数値 */}
                  <div className="grid grid-cols-3 gap-3">
                    <div className="bg-gray-50 rounded-lg p-3">
                      <p className="text-xs text-gray-500">全圃場数</p>
                      <p className="text-2xl font-bold text-gray-900 mt-1">
                        {summary.total_fields}<span className="text-xs font-normal text-gray-500 ml-1">筆</span>
                      </p>
                    </div>
                    <div className="bg-gray-50 rounded-lg p-3">
                      <p className="text-xs text-gray-500">作付け済み</p>
                      <p className="text-2xl font-bold text-green-600 mt-1">
                        {summary.assigned_fields}<span className="text-xs font-normal text-gray-500 ml-1">筆</span>
                      </p>
                    </div>
                    <div className="bg-gray-50 rounded-lg p-3">
                      <p className="text-xs text-gray-500">未割当</p>
                      <div className="flex items-center mt-1">
                        <p className={`text-2xl font-bold ${summary.unassigned_fields > 0 ? 'text-amber-500' : 'text-gray-400'}`}>
                          {summary.unassigned_fields}<span className="text-xs font-normal text-gray-500 ml-1">筆</span>
                        </p>
                        {summary.unassigned_fields > 0 && (
                          <AlertTriangle className="h-4 w-4 text-amber-500 ml-1 flex-shrink-0" />
                        )}
                      </div>
                    </div>
                  </div>

                  {/* 作物別集計 */}
                  {summary.by_crop.length > 0 && (
                    <div>
                      <p className="text-xs font-medium text-gray-500 mb-2">作物別集計</p>
                      <table className="w-full text-sm">
                        <tbody>
                          {summary.by_crop.map((item) => (
                            <tr key={item.crop} className="border-b border-gray-100 last:border-0">
                              <td className="py-1.5 text-gray-900">{item.crop}</td>
                              <td className="py-1.5 text-right text-gray-600">{item.count}筆</td>
                              <td className="py-1.5 text-right text-gray-600">{item.area.toFixed(1)}反</td>
                            </tr>
                          ))}
                          <tr className="font-semibold border-t border-gray-200">
                            <td className="pt-2 text-gray-900">合計</td>
                            <td className="pt-2 text-right text-gray-900">{summary.total_plans}筆</td>
                            <td className="pt-2 text-right text-gray-900">{summary.total_area.toFixed(1)}反</td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  )}

                  {/* クイックアクセス */}
                  <div className="grid grid-cols-2 gap-2 pt-2">
                    <button
                      onClick={() => router.push('/allocation')}
                      className="flex items-center gap-2 px-3 py-2 rounded-md border border-gray-200 hover:bg-green-50 hover:border-green-300 transition-colors text-sm text-gray-700"
                    >
                      <Wheat className="h-4 w-4 text-green-600 flex-shrink-0" />
                      作付け計画
                    </button>
                    <button
                      onClick={() => router.push('/fields')}
                      className="flex items-center gap-2 px-3 py-2 rounded-md border border-gray-200 hover:bg-blue-50 hover:border-blue-300 transition-colors text-sm text-gray-700"
                    >
                      <MapPin className="h-4 w-4 text-blue-600 flex-shrink-0" />
                      圃場管理
                    </button>
                    <button
                      onClick={() => router.push('/reports')}
                      className="flex items-center gap-2 px-3 py-2 rounded-md border border-gray-200 hover:bg-purple-50 hover:border-purple-300 transition-colors text-sm text-gray-700"
                    >
                      <FileText className="h-4 w-4 text-purple-600 flex-shrink-0" />
                      帳票出力
                    </button>
                    <button
                      onClick={() => router.push('/import')}
                      className="flex items-center gap-2 px-3 py-2 rounded-md border border-gray-200 hover:bg-orange-50 hover:border-orange-300 transition-colors text-sm text-gray-700"
                    >
                      <Upload className="h-4 w-4 text-orange-600 flex-shrink-0" />
                      データ取込
                    </button>
                  </div>
                </>
              ) : (
                <div className="py-12 text-center text-gray-500 text-sm">データの取得に失敗しました</div>
              )}
            </div>
          </div>

          {/* ===== メール通知モジュール ===== */}
          <div className="bg-white rounded-lg shadow flex flex-col">
            <div className="px-5 py-4 border-b border-gray-200 flex items-center gap-2">
              <Mail className="h-5 w-5 text-blue-600" />
              <h2 className="text-base font-semibold text-gray-900">メール通知</h2>
            </div>

            <div className="p-5 space-y-4 flex-1">
              {mailLoading ? (
                <div className="flex justify-center py-12">
                  <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
                </div>
              ) : mailStats ? (
                <>
                  {/* 統計 */}
                  <div className="grid grid-cols-2 gap-3">
                    <div className="bg-gray-50 rounded-lg p-3">
                      <p className="text-xs text-gray-500">今日の処理</p>
                      <p className="text-2xl font-bold text-gray-900 mt-1">
                        {mailStats.today_processed}<span className="text-xs font-normal text-gray-500 ml-1">件</span>
                      </p>
                    </div>
                    <div className="bg-gray-50 rounded-lg p-3">
                      <p className="text-xs text-gray-500">LINE通知済み</p>
                      <p className="text-2xl font-bold text-blue-600 mt-1">
                        {mailStats.today_notified}<span className="text-xs font-normal text-gray-500 ml-1">件</span>
                      </p>
                    </div>
                    <div className="bg-gray-50 rounded-lg p-3">
                      <p className="text-xs text-gray-500">フィードバック待ち</p>
                      <div className="flex items-center mt-1">
                        <p className={`text-2xl font-bold ${mailStats.feedback_pending > 0 ? 'text-amber-500' : 'text-gray-400'}`}>
                          {mailStats.feedback_pending}<span className="text-xs font-normal text-gray-500 ml-1">件</span>
                        </p>
                        {mailStats.feedback_pending > 0 && (
                          <Clock className="h-4 w-4 text-amber-500 ml-1 flex-shrink-0" />
                        )}
                      </div>
                    </div>
                    <div className="bg-gray-50 rounded-lg p-3">
                      <p className="text-xs text-gray-500">送信者ルール</p>
                      <p className="text-2xl font-bold text-gray-900 mt-1">
                        {mailStats.total_rules}<span className="text-xs font-normal text-gray-500 ml-1">件</span>
                      </p>
                    </div>
                  </div>

                  {/* クイックアクセス */}
                  <div className="grid grid-cols-2 gap-2 pt-2">
                    <button
                      onClick={() => router.push('/mail/history')}
                      className="flex items-center gap-2 px-3 py-2 rounded-md border border-gray-200 hover:bg-blue-50 hover:border-blue-300 transition-colors text-sm text-gray-700"
                    >
                      <History className="h-4 w-4 text-blue-600 flex-shrink-0" />
                      メール履歴
                    </button>
                    <button
                      onClick={() => router.push('/mail/rules')}
                      className="flex items-center gap-2 px-3 py-2 rounded-md border border-gray-200 hover:bg-blue-50 hover:border-blue-300 transition-colors text-sm text-gray-700"
                    >
                      <Shield className="h-4 w-4 text-blue-600 flex-shrink-0" />
                      ルール管理
                    </button>
                  </div>
                </>
              ) : (
                <div className="py-12 text-center text-gray-500 text-sm">データの取得に失敗しました</div>
              )}
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}
