"use client";

import { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { templatesApi, type TemplateInfo } from "@/lib/api/client";
import { Upload, Loader2, FileSpreadsheet, FileText } from "lucide-react";
import { toast } from "sonner";

export default function SettingsTemplatesPage() {
  const [templates, setTemplates] = useState<TemplateInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [dragOver, setDragOver] = useState(false);

  const loadTemplates = useCallback(async () => {
    try {
      const list = await templatesApi.list();
      setTemplates(list);
    } catch {
      toast.error("加载模板列表失败");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadTemplates();
  }, [loadTemplates]);

  const handleFile = async (file: File) => {
    const ext = file.name.toLowerCase().slice(file.name.lastIndexOf("."));
    if (![".xlsx", ".xltx", ".docx", ".dotx"].includes(ext)) {
      toast.error("仅支持 .xlsx、.xltx、.docx、.dotx 文件");
      return;
    }
    setUploading(true);
    try {
      await templatesApi.upload(file);
      toast.success(`已上传：${file.name}`);
      await loadTemplates();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "上传失败");
    } finally {
      setUploading(false);
    }
  };

  const onDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(false);
    const file = e.dataTransfer.files[0];
    if (file) handleFile(file);
  };

  const onDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(true);
  };

  const onDragLeave = () => setDragOver(false);

  const onSelectFile = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) handleFile(file);
    e.target.value = "";
  };

  const formatDate = (ts: number) =>
    new Date(ts * 1000).toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });

  return (
    <div className="p-6 max-w-4xl">
      <div className="mb-4">
        <a href="/settings" className="text-sm text-muted-foreground hover:text-foreground">
          ← 设置
        </a>
      </div>
      <Card>
        <CardHeader>
          <CardTitle>模板库</CardTitle>
          <p className="text-sm text-muted-foreground">
            上传报价单 Excel（.xlsx / .xltx）或合同 Word（.docx / .dotx），生成报价/合同时可选择使用。
          </p>
        </CardHeader>
        <CardContent className="space-y-6">
          <div
            onDrop={onDrop}
            onDragOver={onDragOver}
            onDragLeave={onDragLeave}
            className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
              dragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25"
            }`}
          >
            <input
              type="file"
              accept=".xlsx,.xltx,.docx,.dotx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.wordprocessingml.template"
              onChange={onSelectFile}
              className="hidden"
              id="template-upload"
            />
            <label htmlFor="template-upload" className="cursor-pointer block">
              <Upload className="h-10 w-10 mx-auto text-muted-foreground" />
              <p className="mt-2 text-sm font-medium">拖拽文件到此处，或点击选择</p>
              <p className="text-xs text-muted-foreground mt-1">仅支持 .xlsx、.xltx、.docx、.dotx</p>
            </label>
            {uploading && (
              <p className="mt-2 text-sm text-muted-foreground flex items-center justify-center gap-1">
                <Loader2 className="h-4 w-4 animate-spin" />
                上传中…
              </p>
            )}
          </div>

          <div>
            <h3 className="text-sm font-medium mb-2">已上传模板</h3>
            {loading ? (
              <p className="text-sm text-muted-foreground flex items-center gap-1">
                <Loader2 className="h-4 w-4 animate-spin" />
                加载中…
              </p>
            ) : templates.length === 0 ? (
              <p className="text-sm text-muted-foreground">暂无模板</p>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>类型</TableHead>
                    <TableHead>文件名</TableHead>
                    <TableHead>大小</TableHead>
                    <TableHead>上传时间</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {templates.map((t) => (
                    <TableRow key={t.name}>
                      <TableCell>
                        {t.type === "excel" ? (
                          <FileSpreadsheet className="h-4 w-4 text-green-600" />
                        ) : (
                          <FileText className="h-4 w-4 text-blue-600" />
                        )}
                      </TableCell>
                      <TableCell className="font-medium">{t.name}</TableCell>
                      <TableCell className="text-muted-foreground">
                        {(t.size / 1024).toFixed(1)} KB
                      </TableCell>
                      <TableCell className="text-muted-foreground">
                        {formatDate(t.uploaded_at)}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
