/**
 * 審核對話框組件
 */

import { useState } from "react";
import { Check, X } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "../ui/dialog";
import { Button } from "../ui/button";
import { Label } from "../ui/label";
import { Textarea } from "../ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../ui/select";
import { REJECTION_REASONS } from "../../constants/purchase-order";
import type { PurchaseOrder } from "../../types/purchase-order";

interface ReviewDialogProps {
  order: PurchaseOrder;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onApprove: (orderId: string) => void;
  onReject: (orderId: string, reason: string) => void;
}

export function ReviewDialog({
  order,
  open,
  onOpenChange,
  onApprove,
  onReject,
}: ReviewDialogProps) {
  const [action, setAction] = useState<"approve" | "reject" | null>(null);
  const [rejectionReason, setRejectionReason] = useState("");
  const [customReason, setCustomReason] = useState("");

  const handleConfirm = () => {
    if (action === "approve") {
      onApprove(order.id);
    } else if (action === "reject") {
      const finalReason =
        rejectionReason === "其他" ? customReason : rejectionReason;
      if (finalReason) {
        onReject(order.id, finalReason);
      }
    }
    handleClose();
  };

  const handleClose = () => {
    setAction(null);
    setRejectionReason("");
    setCustomReason("");
    onOpenChange(false);
  };

  const isValid = () => {
    if (action === "approve") return true;
    if (action === "reject") {
      if (rejectionReason === "其他") {
        return customReason.trim().length > 0;
      }
      return rejectionReason.length > 0;
    }
    return false;
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>審核採購單</DialogTitle>
          <DialogDescription>
            採購單編號：{order.poNumber}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          {/* 採購單資訊摘要 */}
          <div className="bg-muted p-4 rounded-lg space-y-2">
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">申請人：</span>
              <span className="font-medium">{order.createdBy}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">申請單位：</span>
              <span className="font-medium">{order.department}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">廠商：</span>
              <span className="font-medium">{order.supplierName}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">總金額：</span>
              <span className="font-medium">
                ${order.totalAmount.toLocaleString()}
              </span>
            </div>
          </div>

          {/* 選擇審核動作 */}
          {!action && (
            <div className="space-y-3">
              <p className="text-sm text-muted-foreground">請選擇審核動作：</p>
              <div className="flex gap-3">
                <Button
                  onClick={() => setAction("approve")}
                  className="flex-1 gap-2 button-filled-primary"
                >
                  <Check className="h-4 w-4" />
                  審核通過
                </Button>
                <Button
                  onClick={() => setAction("reject")}
                  className="flex-1 gap-2 button-filled-error"
                >
                  <X className="h-4 w-4" />
                  退回
                </Button>
              </div>
            </div>
          )}

          {/* 審核通過確認 */}
          {action === "approve" && (
            <div className="bg-green-50 border-2 border-green-200 p-4 rounded-lg">
              <div className="flex items-center gap-2 mb-2">
                <Check className="h-5 w-5 text-green-600" />
                <span className="font-medium text-green-900">審核通過</span>
              </div>
              <p className="text-sm text-green-700">
                通過後，此採購單將進入「已核准」狀態，可以開始進行採購作業。
              </p>
            </div>
          )}

          {/* 退回原因選擇 */}
          {action === "reject" && (
            <div className="space-y-4">
              <div className="bg-red-50 border-2 border-red-200 p-4 rounded-lg">
                <div className="flex items-center gap-2 mb-2">
                  <X className="h-5 w-5 text-red-600" />
                  <span className="font-medium text-red-900">退回採購單</span>
                </div>
                <p className="text-sm text-red-700">
                  退回後，申請人需要修改後重新送審。
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="rejection-reason">退回原因 *</Label>
                <Select value={rejectionReason} onValueChange={setRejectionReason}>
                  <SelectTrigger
                    id="rejection-reason"
                    className="h-11 border-2 border-input"
                  >
                    <SelectValue placeholder="請選擇退回原因" />
                  </SelectTrigger>
                  <SelectContent>
                    {REJECTION_REASONS.map((reason) => (
                      <SelectItem key={reason.value} value={reason.value}>
                        {reason.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {rejectionReason === "其他" && (
                <div className="space-y-2">
                  <Label htmlFor="custom-reason">請說明原因 *</Label>
                  <Textarea
                    id="custom-reason"
                    value={customReason}
                    onChange={(e) => setCustomReason(e.target.value)}
                    placeholder="請輸入退回原因..."
                    className="border-2 border-input min-h-[100px]"
                  />
                </div>
              )}
            </div>
          )}
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={handleClose}
            className="button-outlined-primary"
          >
            取消
          </Button>
          {action && (
            <Button
              onClick={handleConfirm}
              disabled={!isValid()}
              className={
                action === "approve"
                  ? "button-filled-primary"
                  : "button-filled-error"
              }
            >
              確認{action === "approve" ? "通過" : "退回"}
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
