import { useState } from "react";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useOrder } from "@/features/dashboard/hooks/useOrder";
import { useKisRuntimeStore } from "@/features/dashboard/store/use-kis-runtime-store";
import type {
  DashboardOrderSide,
  DashboardStockItem,
} from "@/features/dashboard/types/dashboard.types";

interface OrderFormProps {
  stock?: DashboardStockItem;
}

/**
 * @description 대시보드 주문 패널에서 매수/매도 주문을 입력하고 전송합니다.
 * @see features/dashboard/hooks/useOrder.ts placeOrder - 주문 API 호출
 * @see features/dashboard/components/DashboardContainer.tsx OrderForm - 우측 주문 패널 렌더링
 */
export function OrderForm({ stock }: OrderFormProps) {
  const verifiedCredentials = useKisRuntimeStore(
    (state) => state.verifiedCredentials,
  );
  const { placeOrder, isLoading, error } = useOrder();

  // ========== FORM STATE ==========
  const [price, setPrice] = useState<string>(stock?.currentPrice.toString() || "");
  const [quantity, setQuantity] = useState<string>("");
  const [activeTab, setActiveTab] = useState<"buy" | "sell">("buy");

  // ========== ORDER HANDLER ==========
  const handleOrder = async (side: DashboardOrderSide) => {
    if (!stock || !verifiedCredentials) return;

    const priceNum = parseInt(price.replace(/,/g, ""), 10);
    const qtyNum = parseInt(quantity.replace(/,/g, ""), 10);

    if (Number.isNaN(priceNum) || priceNum <= 0) {
      alert("가격을 올바르게 입력해 주세요.");
      return;
    }
    if (Number.isNaN(qtyNum) || qtyNum <= 0) {
      alert("수량을 올바르게 입력해 주세요.");
      return;
    }
    if (!verifiedCredentials.accountNo) {
      alert("계좌번호가 없습니다. 설정에서 계좌번호를 입력해 주세요.");
      return;
    }

    const response = await placeOrder(
      {
        symbol: stock.symbol,
        side,
        orderType: "limit",
        price: priceNum,
        quantity: qtyNum,
        accountNo: verifiedCredentials.accountNo,
        accountProductCode: "01",
      },
      verifiedCredentials,
    );

    if (response?.orderNo) {
      alert(`주문 전송 완료: ${response.orderNo}`);
      setQuantity("");
    }
  };

  const totalPrice =
    parseInt(price.replace(/,/g, "") || "0", 10) *
    parseInt(quantity.replace(/,/g, "") || "0", 10);

  const setPercent = (pct: string) => {
    // TODO: 계좌 잔고 연동 시 퍼센트 자동 계산으로 교체
    console.log("Percent clicked:", pct);
  };

  const isMarketDataAvailable = Boolean(stock);

  return (
    <div className="h-full border-l border-border bg-background p-3 dark:border-brand-800/45 dark:bg-brand-950/55 sm:p-4">
      <Tabs
        value={activeTab}
        onValueChange={(value) => setActiveTab(value as "buy" | "sell")}
        className="flex h-full w-full flex-col"
      >
        {/* ========== ORDER SIDE TABS ========== */}
        <TabsList className="mb-3 grid h-10 w-full grid-cols-2 gap-1 border border-brand-200/70 bg-muted/35 p-1 dark:border-brand-700/50 dark:bg-brand-900/28 sm:mb-4">
          <TabsTrigger
            value="buy"
            className="!h-full rounded-md border border-transparent text-foreground/75 transition-colors dark:text-brand-100/75 data-[state=active]:border-red-400/60 data-[state=active]:bg-red-600 data-[state=active]:text-white data-[state=active]:shadow-[0_0_0_1px_rgba(248,113,113,0.45)]"
          >
            매수
          </TabsTrigger>
          <TabsTrigger
            value="sell"
            className="!h-full rounded-md border border-transparent text-foreground/75 transition-colors dark:text-brand-100/75 data-[state=active]:border-blue-400/65 data-[state=active]:bg-blue-600 data-[state=active]:text-white data-[state=active]:shadow-[0_0_0_1px_rgba(96,165,250,0.45)]"
          >
            매도
          </TabsTrigger>
        </TabsList>

        {/* ========== BUY TAB ========== */}
        <TabsContent
          value="buy"
          className="flex flex-1 flex-col space-y-3 data-[state=inactive]:hidden sm:space-y-4"
        >
          <OrderInputs
            type="buy"
            price={price}
            setPrice={setPrice}
            quantity={quantity}
            setQuantity={setQuantity}
            totalPrice={totalPrice}
            disabled={!isMarketDataAvailable}
            hasError={Boolean(error)}
            errorMessage={error}
          />
          <PercentButtons onSelect={setPercent} />
          <Button
            className="mt-auto h-11 w-full bg-red-600 text-base text-white shadow-sm ring-1 ring-red-300/35 hover:bg-red-700 dark:bg-red-500 dark:ring-red-300/45 dark:hover:bg-red-400 sm:h-12 sm:text-lg"
            disabled={isLoading || !isMarketDataAvailable}
            onClick={() => handleOrder("buy")}
          >
            {isLoading ? <Loader2 className="mr-2 animate-spin" /> : "매수하기"}
          </Button>
        </TabsContent>

        {/* ========== SELL TAB ========== */}
        <TabsContent
          value="sell"
          className="flex flex-1 flex-col space-y-3 data-[state=inactive]:hidden sm:space-y-4"
        >
          <OrderInputs
            type="sell"
            price={price}
            setPrice={setPrice}
            quantity={quantity}
            setQuantity={setQuantity}
            totalPrice={totalPrice}
            disabled={!isMarketDataAvailable}
            hasError={Boolean(error)}
            errorMessage={error}
          />
          <PercentButtons onSelect={setPercent} />
          <Button
            className="mt-auto h-11 w-full bg-blue-600 text-base text-white shadow-sm ring-1 ring-blue-300/35 hover:bg-blue-700 dark:bg-blue-500 dark:ring-blue-300/45 dark:hover:bg-blue-400 sm:h-12 sm:text-lg"
            disabled={isLoading || !isMarketDataAvailable}
            onClick={() => handleOrder("sell")}
          >
            {isLoading ? <Loader2 className="mr-2 animate-spin" /> : "매도하기"}
          </Button>
        </TabsContent>
      </Tabs>
    </div>
  );
}

/**
 * @description 주문 입력 영역(가격/수량/총액)을 렌더링합니다.
 * @see features/dashboard/components/order/OrderForm.tsx OrderForm - 매수/매도 탭에서 공용 호출
 */
function OrderInputs({
  type,
  price,
  setPrice,
  quantity,
  setQuantity,
  totalPrice,
  disabled,
  hasError,
  errorMessage,
}: {
  type: "buy" | "sell";
  price: string;
  setPrice: (v: string) => void;
  quantity: string;
  setQuantity: (v: string) => void;
  totalPrice: number;
  disabled: boolean;
  hasError: boolean;
  errorMessage: string | null;
}) {
  return (
    <div className="space-y-3 sm:space-y-4">
      <div className="flex justify-between text-xs text-muted-foreground">
        <span>주문가능</span>
        <span>- {type === "buy" ? "KRW" : "주"}</span>
      </div>

      {hasError && (
        <div className="rounded bg-destructive/10 p-2 text-xs text-destructive break-keep">
          {errorMessage}
        </div>
      )}

      <div className="grid grid-cols-4 items-center gap-2">
        <span className="text-xs font-medium sm:text-sm">
          {type === "buy" ? "매수가격" : "매도가격"}
        </span>
        <Input
          className="col-span-3 text-right font-mono dark:border-brand-700/55 dark:bg-black/25 dark:text-brand-100"
          placeholder="0"
          value={price}
          onChange={(e) => setPrice(e.target.value)}
          disabled={disabled}
        />
      </div>

      <div className="grid grid-cols-4 items-center gap-2">
        <span className="text-xs font-medium sm:text-sm">주문수량</span>
        <Input
          className="col-span-3 text-right font-mono dark:border-brand-700/55 dark:bg-black/25 dark:text-brand-100"
          placeholder="0"
          value={quantity}
          onChange={(e) => setQuantity(e.target.value)}
          disabled={disabled}
        />
      </div>

      <div className="grid grid-cols-4 items-center gap-2">
        <span className="text-xs font-medium sm:text-sm">주문총액</span>
        <Input
          className="col-span-3 bg-muted/50 text-right font-mono dark:border-brand-700/55 dark:bg-black/20 dark:text-brand-100"
          value={totalPrice.toLocaleString()}
          readOnly
          disabled={disabled}
        />
      </div>
    </div>
  );
}

/**
 * @description 주문 비율(10/25/50/100%) 단축 버튼을 표시합니다.
 * @see features/dashboard/components/order/OrderForm.tsx setPercent - 버튼 클릭 이벤트 처리
 */
function PercentButtons({ onSelect }: { onSelect: (pct: string) => void }) {
  return (
    <div className="mt-2 grid grid-cols-4 gap-2">
      {["10%", "25%", "50%", "100%"].map((pct) => (
        <Button
          key={pct}
          variant="outline"
          size="sm"
          className="text-xs"
          onClick={() => onSelect(pct)}
        >
          {pct}
        </Button>
      ))}
    </div>
  );
}
