"use client";

import React, { useState } from "react";
import { Table, ArrowLeft, ArrowRight, CheckCircle, Database } from "lucide-react";
import { Connection, TableInfo } from "../types/redesigned";

interface TableStepProps {
  fromConnection?: Connection;
  toConnection?: Connection;
  fromTable?: TableInfo;
  toTable?: TableInfo;
  onFromTableChange: (table: TableInfo) => void;
  onToTableChange: (table: TableInfo) => void;
  onNext: () => void;
  onBack: () => void;
}

// 임시 테이블 데이터
const mockTables: TableInfo[] = [
  {
    name: "users",
    schema: "public",
    columns: [
      { name: "id", type: "integer", nullable: false, primaryKey: true },
      { name: "name", type: "varchar", nullable: false, primaryKey: false },
      { name: "email", type: "varchar", nullable: true, primaryKey: false },
      { name: "created_at", type: "timestamp", nullable: false, primaryKey: false },
    ],
    rowCount: 1250,
  },
  {
    name: "orders",
    schema: "public",
    columns: [
      { name: "id", type: "integer", nullable: false, primaryKey: true },
      { name: "user_id", type: "integer", nullable: false, primaryKey: false, foreignKey: true },
      { name: "product_name", type: "varchar", nullable: false, primaryKey: false },
      { name: "amount", type: "decimal", nullable: false, primaryKey: false },
      { name: "order_date", type: "timestamp", nullable: false, primaryKey: false },
    ],
    rowCount: 3420,
  },
  {
    name: "products",
    schema: "public",
    columns: [
      { name: "id", type: "integer", nullable: false, primaryKey: true },
      { name: "name", type: "varchar", nullable: false, primaryKey: false },
      { name: "price", type: "decimal", nullable: false, primaryKey: false },
      { name: "category", type: "varchar", nullable: true, primaryKey: false },
    ],
    rowCount: 156,
  },
];

export const TableStep: React.FC<TableStepProps> = ({
  fromConnection,
  toConnection,
  fromTable,
  toTable,
  onFromTableChange,
  onToTableChange,
  onNext,
  onBack,
}) => {
  const [selectedFromTable, setSelectedFromTable] = useState<string>(fromTable?.name || "");
  const [selectedToTable, setSelectedToTable] = useState<string>(toTable?.name || "");

  const handleFromTableSelect = (tableName: string) => {
    const table = mockTables.find((t) => t.name === tableName);
    if (table) {
      setSelectedFromTable(tableName);
      onFromTableChange(table);
    }
  };

  const handleToTableSelect = (tableName: string) => {
    const table = mockTables.find((t) => t.name === tableName);
    if (table) {
      setSelectedToTable(tableName);
      onToTableChange(table);
    }
  };

  const canProceed = selectedFromTable && selectedToTable;

  return (
    <div className="space-y-8">
      <div className="text-center">
        <h2 className="mb-2 text-2xl font-bold text-gray-900">테이블 선택</h2>
        <p className="text-muted-foreground">소스 테이블과 대상 테이블을 선택하세요</p>
      </div>

      {/* 연결 정보 표시 */}
      <div className="rounded-lg bg-gray-50 p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Database className="text-primary h-5 w-5" />
            <span className="font-medium text-gray-900">{fromConnection?.name}</span>
            <span className="text-sm text-gray-500">→</span>
            <Database className="h-5 w-5 text-green-600" />
            <span className="font-medium text-gray-900">{toConnection?.name}</span>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-8 lg:grid-cols-2">
        {/* FROM 테이블 */}
        <div className="space-y-4">
          <div className="flex items-center gap-2">
            <div className="bg-primary/20 flex h-8 w-8 items-center justify-center rounded-full">
              <span className="text-primary font-bold">1</span>
            </div>
            <h3 className="text-lg font-semibold text-gray-900">소스 테이블</h3>
            <span className="text-sm text-gray-500">(FROM)</span>
          </div>

          <div className="space-y-2">
            {mockTables.map((table) => (
              <div
                key={table.name}
                className={`cursor-pointer rounded-lg border-2 p-4 transition-all duration-200 ${
                  selectedFromTable === table.name
                    ? "border-primary bg-accent shadow-md"
                    : "hover:bg-blue-25 border-gray-200 bg-white hover:border-blue-300"
                }`}
                onClick={() => handleFromTableSelect(table.name)}
              >
                <div className="flex items-center gap-3">
                  <Table className="text-primary h-6 w-6" />
                  <div className="flex-1">
                    <h4 className="font-medium text-gray-900">{table.name}</h4>
                    <p className="text-muted-foreground text-sm">{table.columns.length}개 컬럼</p>
                    <p className="text-xs text-gray-500">{table.rowCount?.toLocaleString()}개 행</p>
                  </div>
                  {selectedFromTable === table.name && <CheckCircle className="text-primary h-5 w-5" />}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* TO 테이블 */}
        <div className="space-y-4">
          <div className="flex items-center gap-2">
            <div className="flex h-8 w-8 items-center justify-center rounded-full bg-green-100">
              <span className="font-bold text-green-600">2</span>
            </div>
            <h3 className="text-lg font-semibold text-gray-900">대상 테이블</h3>
            <span className="text-sm text-gray-500">(TO)</span>
          </div>

          <div className="space-y-2">
            {mockTables.map((table) => (
              <div
                key={table.name}
                className={`cursor-pointer rounded-lg border-2 p-4 transition-all duration-200 ${
                  selectedToTable === table.name
                    ? "border-green-500 bg-green-50 shadow-md"
                    : "hover:bg-green-25 border-gray-200 bg-white hover:border-green-300"
                }`}
                onClick={() => handleToTableSelect(table.name)}
              >
                <div className="flex items-center gap-3">
                  <Table className="h-6 w-6 text-green-600" />
                  <div className="flex-1">
                    <h4 className="font-medium text-gray-900">{table.name}</h4>
                    <p className="text-muted-foreground text-sm">{table.columns.length}개 컬럼</p>
                    <p className="text-xs text-gray-500">{table.rowCount?.toLocaleString()}개 행</p>
                  </div>
                  {selectedToTable === table.name && <CheckCircle className="h-5 w-5 text-green-600" />}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* 버튼들 */}
      <div className="flex justify-between">
        <button
          onClick={onBack}
          className="text-muted-foreground flex items-center gap-2 rounded-lg bg-gray-100 px-6 py-3 font-medium transition-all duration-200 hover:bg-gray-200"
        >
          <ArrowLeft className="h-4 w-4" />
          이전 단계
        </button>

        <button
          onClick={onNext}
          disabled={!canProceed}
          className={`flex items-center gap-2 rounded-lg px-6 py-3 font-medium transition-all duration-200 ${
            canProceed
              ? "bg-orange-500 text-white shadow-md hover:bg-orange-600 hover:shadow-lg"
              : "cursor-not-allowed bg-gray-300 text-gray-500"
          }`}
        >
          다음 단계: 필드 매핑
          <ArrowRight className="h-4 w-4" />
        </button>
      </div>
    </div>
  );
};
