'use client';

import { useState } from 'react';
import { api } from '@/lib/api';
import Navbar from '@/components/Navbar';
import { FileDown, Eye, Loader2 } from 'lucide-react';

const downloadPdf = async (url: string, filename: string) => {
  const response = await api.get(url, { responseType: 'blob' });
  const blob = new Blob([response.data], { type: 'application/pdf' });
  const downloadUrl = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = downloadUrl;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  link.remove();
  window.URL.revokeObjectURL(downloadUrl);
};

const previewPdf = async (url: string) => {
  const response = await api.get(url, { responseType: 'blob' });
  const blob = new Blob([response.data], { type: 'application/pdf' });
  const previewUrl = window.URL.createObjectURL(blob);
  window.open(previewUrl, '_blank');
};

export default function ReportsPage() {
  const [year, setYear] = useState<number>(new Date().getFullYear());
  const [busy, setBusy] = useState<string | null>(null);

  const handleAction = async (action: 'download' | 'preview', type: 'kyosai' | 'chusankan') => {
    const key = `${action}-${type}`;
    setBusy(key);
    try {
      const url = `/reports/${type}/${year}/`;
      if (action === 'download') {
        const filename = type === 'kyosai'
          ? `水稲共済細目書_${year}.pdf`
          : `中山間交付金申請書_${year}.pdf`;
        await downloadPdf(url, filename);
      } else {
        await previewPdf(url);
      }
    } catch (error) {
      console.error(`${action} failed:`, error);
      alert(`${action === 'download' ? 'ダウンロード' : 'プレビュー'}に失敗しました`);
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Navbar />
      <div className="max-w-2xl 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="bg-white rounded-lg shadow p-6">
          <div className="mb-6">
            <label htmlFor="year" className="block text-sm font-medium text-gray-700 mb-2">
              対象年度
            </label>
            <select
              id="year"
              value={year}
              onChange={(e) => setYear(parseInt(e.target.value))}
              className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 w-full max-w-xs"
            >
              {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - 2 + i).map((y) => (
                <option key={y} value={y}>{y}年</option>
              ))}
            </select>
          </div>

          <div className="space-y-4">
            {/* 水稲共済細目書 */}
            <div className="border rounded-lg p-4">
              <h3 className="font-medium text-gray-900 mb-3">水稲共済細目書</h3>
              <div className="flex gap-3">
                <button
                  onClick={() => handleAction('preview', 'kyosai')}
                  disabled={busy !== null}
                  className="flex-1 flex items-center justify-center px-4 py-2.5 border border-green-600 text-green-700 rounded-md hover:bg-green-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  {busy === 'preview-kyosai' ? (
                    <><Loader2 className="h-4 w-4 mr-2 animate-spin" />生成中...</>
                  ) : (
                    <><Eye className="h-4 w-4 mr-2" />プレビュー</>
                  )}
                </button>
                <button
                  onClick={() => handleAction('download', 'kyosai')}
                  disabled={busy !== null}
                  className="flex-1 flex items-center justify-center px-4 py-2.5 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  {busy === 'download-kyosai' ? (
                    <><Loader2 className="h-4 w-4 mr-2 animate-spin" />ダウンロード中...</>
                  ) : (
                    <><FileDown className="h-4 w-4 mr-2" />ダウンロード</>
                  )}
                </button>
              </div>
            </div>

            {/* 中山間交付金申請書 */}
            <div className="border rounded-lg p-4">
              <h3 className="font-medium text-gray-900 mb-3">中山間交付金申請書</h3>
              <div className="flex gap-3">
                <button
                  onClick={() => handleAction('preview', 'chusankan')}
                  disabled={busy !== null}
                  className="flex-1 flex items-center justify-center px-4 py-2.5 border border-blue-600 text-blue-700 rounded-md hover:bg-blue-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  {busy === 'preview-chusankan' ? (
                    <><Loader2 className="h-4 w-4 mr-2 animate-spin" />生成中...</>
                  ) : (
                    <><Eye className="h-4 w-4 mr-2" />プレビュー</>
                  )}
                </button>
                <button
                  onClick={() => handleAction('download', 'chusankan')}
                  disabled={busy !== null}
                  className="flex-1 flex items-center justify-center px-4 py-2.5 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  {busy === 'download-chusankan' ? (
                    <><Loader2 className="h-4 w-4 mr-2 animate-spin" />ダウンロード中...</>
                  ) : (
                    <><FileDown className="h-4 w-4 mr-2" />ダウンロード</>
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
