/**
 * 建立/編輯採購單頁面 - Mobile-first RWD
 */

import { useState } from "react";
import { ArrowLeft, AlertCircle, Calendar, Building2, FileText, Info, Store as StoreIcon, Warehouse as WarehouseIcon, User, Plus, Trash2 } from "lucide-react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Textarea } from "./ui/textarea";
import { Alert, AlertDescription } from "./ui/alert";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "./ui/select";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "./ui/alert-dialog";
import { PurchaseOrderItemsTable } from "./purchase-order/PurchaseOrderItemsTable";
import type { PurchaseOrder, Supplier, RequesterType } from "../types/purchase-order";
import type { Store, Warehouse } from "../types/requester";
import { usePurchaseOrderForm } from "../hooks/usePurchaseOrderForm";
import { STATUS_CONFIG } from "../constants/purchase-order";
import {
  validatePurchaseOrder,
  filterValidItems,
  calculateTotalAmount,
  generatePONumber,
  getTodayDate,
  isPriceAlert,
  formatCurrency,
} from "../utils/purchase-order";

interface CreatePurchaseOrderPageProps {
  order?: PurchaseOrder;
  onSave: (order: PurchaseOrder) => void;
  onCancel: () => void;
  onDelete?: (id: string) => void;
  suppliers: Supplier[];
  stores: Store[];
  warehouses: Warehouse[];
}

export default function CreatePurchaseOrderPage({
  order,
  onSave,
  onCancel,
  onDelete,
  suppliers,
  stores,
  warehouses,
}: CreatePurchaseOrderPageProps) {
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  
  const {
    supplierId,
    expectedDate,
    items,
    notes,
    status,
    selectedSupplier,
    isOrderSent,
    requesterType,
    requesterId,
    setSupplierId,
    setExpectedDate,
    setNotes,
    setStatus,
    setRequesterType,
    setRequesterId,
    addItem,
    removeItem,
    updateItem,
  } = usePurchaseOrderForm({ order, suppliers });

  const totalAmount = calculateTotalAmount(items);
  const isValid = validatePurchaseOrder(supplierId, expectedDate, items);
  const hasPriceAlerts = items.some((item) => isPriceAlert(item.unitPrice, item.previousPrice));

  // 根據類型選擇對應的清單
  const requesterList = requesterType === "store" ? stores : warehouses;
  const selectedRequester = requesterList.find((r) => r.id === requesterId);

  const handleSave = () => {
    if (!isValid || !requesterId) return;

    const validItems = filterValidItems(items);
    if (validItems.length === 0) return;

    const supplier = suppliers.find((s) => s.id === supplierId);
    if (!supplier) return;

    const requester = requesterList.find((r) => r.id === requesterId);
    if (!requester) return;

    const newOrder: PurchaseOrder = {
      id: order?.id || `po-${Date.now()}`,
      poNumber: order?.poNumber || generatePONumber(),
      supplierId,
      supplierName: supplier.name,
      expectedDate,
      status,
      items: validItems,
      totalAmount: calculateTotalAmount(validItems),
      createdAt: order?.createdAt || getTodayDate(),
      createdBy: order?.createdBy || "系統使用者",
      requesterType,
      requesterId,
      requesterName: requester.name,
      department: requester.name, // 保留相容性
      notes,
    };

    onSave(newOrder);
  };

  const handleDelete = () => {
    if (order && onDelete) {
      onDelete(order.id);
      onCancel(); // 刪除後返回列表頁
    }
    setShowDeleteDialog(false);
  };

  const hasSupplier = !!supplierId;
  const hasRequester = !!requesterId;
  const hasItems = items.length > 0 && items.some(item => item.productId && item.quantity > 0);
  const canSave = isValid && hasRequester && hasItems;

  // 計算 disabled 原因
  const getDisabledReason = () => {
    if (!requesterId) return "請先選擇申請單位";
    if (!supplierId) return "請先選擇供應商";
    if (!expectedDate) return "請填寫預計到貨日";
    if (!hasItems) return "至少新增 1 項有效商品";
    return "";
  };

  return (
    <div className="min-h-screen bg-background pb-32 md:pb-0">
      {/* Header */}
      <div className="sticky top-0 z-20 bg-background border-b-2 border-border p-4 md:p-6">
        <div className="max-w-6xl mx-auto">
          {/* 返回按鈕 */}
          <div className="flex items-center gap-2 mb-4">
            <Button
              variant="outline"
              size="sm"
              onClick={onCancel}
              className="gap-2 button-outlined-primary"
            >
              <ArrowLeft className="h-4 w-4" />
              <span className="hidden sm:inline">返回</span>
            </Button>
          </div>

          {/* 頁面標題 */}
          <div>
            <h1>{order ? "編輯採購單" : "建立採購單"}</h1>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-6xl mx-auto px-4 md:px-6 py-6 space-y-6">
        {/* 基本資訊卡片 */}
        <div className="bg-card rounded-lg border-2 border-border p-6">
          <div className="flex items-center gap-2 mb-6">
            <div className="flex items-center justify-center w-8 h-8 rounded-full border-2 border-muted text-muted-foreground shrink-0">
              1
            </div>
            <h2 className="text-muted-foreground">基本資訊</h2>
          </div>

          {/* 已寄出訂單提示 */}
          {isOrderSent && (
            <Alert className="mb-6">
              <Info className="h-4 w-4" />
              <AlertDescription>
                此採購單已寄出，僅可修改訂單狀態、預計到貨日及備註
              </AlertDescription>
            </Alert>
          )}

          <div className="space-y-4">
            {/* 訂單狀態（編輯模式時顯示） */}
            {order && (
              <div>
                <label htmlFor="status" className="caption text-muted-foreground mb-2 flex items-center gap-2">
                  訂單狀態 <span className="text-destructive">*</span>
                </label>
                <Select value={status} onValueChange={(value: any) => setStatus(value)}>
                  <SelectTrigger id="status" className="h-12 border-2 border-input">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {Object.entries(STATUS_CONFIG).map(([key, config]) => (
                      <SelectItem key={key} value={key}>
                        {config.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}

            {/* 申請人資訊 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* 申請人類型 */}
              <div>
                <label htmlFor="requesterType" className="caption text-muted-foreground mb-2">
                  申請人類型 <span className="text-destructive">*</span>
                </label>
                <Select
                  value={requesterType}
                  onValueChange={(value: RequesterType) => {
                    setRequesterType(value);
                    setRequesterId(""); // 重置選擇的單位
                  }}
                  disabled={isOrderSent}
                >
                  <SelectTrigger id="requesterType" className="h-12 border-2 border-input">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="store">
                      <div className="flex items-center gap-2">
                        <StoreIcon className="h-4 w-4" />
                        <span>門市</span>
                      </div>
                    </SelectItem>
                    <SelectItem value="warehouse">
                      <div className="flex items-center gap-2">
                        <WarehouseIcon className="h-4 w-4" />
                        <span>倉庫</span>
                      </div>
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* 申請單位 */}
              <div>
                <label htmlFor="requester" className="caption text-muted-foreground mb-2">
                  {requesterType === "store" ? "門市" : "倉庫"} <span className="text-destructive">*</span>
                </label>
                <Select
                  value={requesterId}
                  onValueChange={setRequesterId}
                  disabled={isOrderSent}
                >
                  <SelectTrigger id="requester" className="h-12 border-2 border-input">
                    <SelectValue placeholder={`請選擇${requesterType === "store" ? "門市" : "倉庫"}`} />
                  </SelectTrigger>
                  <SelectContent>
                    {requesterList.map((requester) => (
                      <SelectItem key={requester.id} value={requester.id}>
                        <div>
                          <div>{requester.name}</div>
                          {requester.address && (
                            <div className="caption text-muted-foreground">
                              {requester.address}
                            </div>
                          )}
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 採購資訊 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* 供應商選擇 */}
              <div>
                <label htmlFor="supplier" className="caption text-muted-foreground mb-2">
                  供應商 <span className="text-destructive">*</span>
                </label>
                <Select
                  value={supplierId}
                  onValueChange={setSupplierId}
                  disabled={isOrderSent}
                >
                  <SelectTrigger id="supplier" className="h-12 border-2 border-input">
                    <SelectValue placeholder="請選擇供應商" />
                  </SelectTrigger>
                  <SelectContent>
                    {suppliers.map((supplier) => (
                      <SelectItem key={supplier.id} value={supplier.id}>
                        <div>
                          <div>{supplier.name}</div>
                          <div className="caption text-muted-foreground">
                            {supplier.contact} · {supplier.phone}
                          </div>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 預計到貨日 */}
              <div>
                <label htmlFor="expectedDate" className="caption text-muted-foreground mb-2">
                  預計到貨日 <span className="text-destructive">*</span>
                </label>
                <div className="relative">
                  <Input
                    id="expectedDate"
                    type="date"
                    value={expectedDate}
                    onChange={(e) => setExpectedDate(e.target.value)}
                    min={getTodayDate()}
                    className="h-12 border-2 border-input pr-10 [&::-webkit-calendar-picker-indicator]:opacity-0 [&::-webkit-calendar-picker-indicator]:absolute [&::-webkit-calendar-picker-indicator]:right-0 [&::-webkit-calendar-picker-indicator]:w-10 [&::-webkit-calendar-picker-indicator]:h-12 [&::-webkit-calendar-picker-indicator]:cursor-pointer"
                  />
                  <Calendar className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground pointer-events-none" />
                </div>
              </div>
            </div>

            {/* 備註 */}
            <div>
              <label htmlFor="notes" className="caption text-muted-foreground mb-2">
                備註
              </label>
              <Textarea
                id="notes"
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="選填：特殊要求或注意事項"
                rows={3}
                className="border-2 border-input resize-none"
              />
            </div>
          </div>
        </div>

        {/* 採購商品區 */}
        <div className={`bg-card rounded-lg border-2 border-border p-6 transition-opacity ${!hasSupplier ? "opacity-60" : ""}`}>
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center gap-2">
              <div className="flex items-center justify-center w-8 h-8 rounded-full border-2 border-muted text-muted-foreground shrink-0">
                2
              </div>
              <h2 className="text-muted-foreground">採購商品</h2>
            </div>
            {!isOrderSent && (
              <Button
                onClick={addItem}
                disabled={!hasSupplier}
                className="gap-2 h-12 button-filled-primary"
              >
                <Plus className="h-5 w-5" />
                新增商品
              </Button>
            )}
          </div>

          {/* 未選擇供應商時的提示 */}
          {!hasSupplier && (
            <Alert className="mb-6">
              <Info className="h-4 w-4" />
              <AlertDescription>
                請先在步驟 1 中選擇供應商後才能新增商品
              </AlertDescription>
            </Alert>
          )}

          {/* 商品表格 */}
          <PurchaseOrderItemsTable
            items={items}
            supplier={selectedSupplier}
            isReadOnly={isOrderSent}
            isDisabled={!hasSupplier}
            onAddItem={addItem}
            onRemoveItem={removeItem}
            onItemChange={updateItem}
          />

          {/* 價格警示提示 */}
          {!isOrderSent && hasPriceAlerts && hasSupplier && (
            <Alert variant="destructive" className="mt-6">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                部分商品單價比上次採購價高出超過 5%，請確認是否正確。
              </AlertDescription>
            </Alert>
          )}

          {/* 總金額 */}
          {hasSupplier && items.length > 0 && (
            <div className="flex justify-between items-center pt-6 mt-6 border-t-2 border-border">
              <span className="text-muted-foreground">總金額</span>
              <span className="text-primary-main">{formatCurrency(totalAmount)}</span>
            </div>
          )}
        </div>

        {/* 操作按鈕 - 桌面版 */}
        <div className="hidden md:block">
          {!canSave && (
            <Alert variant="destructive" className="mb-4">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{getDisabledReason()}</AlertDescription>
            </Alert>
          )}
          <div className="flex justify-end gap-4 pt-6">
            <Button
              variant="outline"
              onClick={onCancel}
              className="h-12 button-outlined-primary"
            >
              取消
            </Button>
            <Button
              onClick={handleSave}
              disabled={!canSave}
              className="h-12 button-filled-primary"
            >
              {order ? "更新採購單" : "建立採購單"}
            </Button>
            {order && (
              <Button
                variant="destructive"
                onClick={() => setShowDeleteDialog(true)}
                className="h-12 button-filled-destructive"
              >
                <Trash2 className="h-5 w-5" />
                刪除採購單
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* 操作按鈕 - 手機版（固定底部） */}
      <div className="fixed bottom-0 left-0 right-0 bg-card border-t-2 border-border p-4 md:hidden z-10">
        {!canSave && (
          <Alert variant="destructive" className="mb-4">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{getDisabledReason()}</AlertDescription>
          </Alert>
        )}
        <div className="flex gap-4">
          <Button
            variant="outline"
            onClick={onCancel}
            className="flex-1 h-12 button-outlined-primary"
          >
            取消
          </Button>
          <Button
            onClick={handleSave}
            disabled={!canSave}
            className="flex-1 h-12 button-filled-primary"
          >
            {order ? "更新採購單" : "建立採購單"}
          </Button>
          {order && (
            <Button
              variant="destructive"
              onClick={() => setShowDeleteDialog(true)}
              className="flex-1 h-12 button-filled-destructive"
            >
              <Trash2 className="h-5 w-5" />
              刪除採購單
            </Button>
          )}
        </div>
      </div>

      {/* 刪除確認對話框 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>確認刪除採購單</AlertDialogTitle>
            <AlertDialogDescription>
              確定要刪除這張採購單嗎？此操作無法撤銷。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="h-12 button-outlined-primary">
              取消
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="h-12 button-filled-destructive"
            >
              刪除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}