"use client"
import PageBreadcrumb from "@/components/common/PageBreadCrumb2";
import ComponentCard2 from '@/components/common/ComponentCard2';
import CtTable1 from '@/components/tables/CtTable1';
import React from "react";
import Badge from "@/components/ui/badge/Badge";
import Image from "next/image";
import { useEffect, useState } from 'react';
import api, { convertDateTime3 } from '@/lib/_AG';
import { useForm } from 'react-hook-form';



const SEARCH_LABEL_WIDTH = 24;
const COUNT_PER_PAGE = 10;
const PAGE_NUM_COUNT = 5;


const ModalForm = ({ item, onClose }: { item: any; onClose: () => void }) => {
  const { register, handleSubmit } = useForm({
    defaultValues: {
      name: item.user.name,
      role: item.user.role,
      address: item.projectName,
      status: item.status,
    },
  });
  

  // 수정 api 연결 
  const onSubmit = (data: any) => {
    console.log("수정된 데이터:", data);
    onClose();
  };


  return (
    <form onSubmit={handleSubmit(onSubmit)} className="p-6 space-y-4">
      <h2 className="text-lg font-semibold">대리점 정보 수정</h2>
      <div>
        <label>이름</label>
        <input {...register("name")} className="w-full border px-3 py-2 rounded" />
      </div>
      <div>
        <label>지점명</label>
        <input {...register("role")} className="w-full border px-3 py-2 rounded" />
      </div>
      <div>
        <label>주소</label>
        <input {...register("address")} className="w-full border px-3 py-2 rounded" />
      </div>
      <div>
        <label>상태</label>
        <select {...register("status")} className="w-full border px-3 py-2 rounded">
          <option value="정상">정상</option>
          <option value="장애">장애</option>
        </select>
      </div>
      <div className="flex justify-end gap-2">
        <button type="button" onClick={onClose} className="px-4 py-2 bg-gray-300 rounded">
          취소
        </button>
        <button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded">
          저장
        </button>
      </div>
    </form>
  );
}

const handleClickRow = (item: any, row: number) => {
  console.log('page change', row);
  alert(row);
};


const headerColumns = [
  {
    title: "대리점",
    key: "user",
    renderItem: (item: any, rowIndex: number) => (
      <div className="flex items-center gap-3">
        {/* <button onClick={() => handleClickTableRow2(rowIndex)}></button> */}
        <div className="w-10 h-10 overflow-hidden rounded-full">
          <Image
            width={40}
            height={40}
            src={item.user.image}
            alt={item.user.name}
          />
        </div>
        <div>
          <span className="block font-medium text-gray-800 text-theme-sm dark:text-white/90">
            {item.user.name}
          </span>
          <span className="block text-gray-500 text-theme-xs dark:text-gray-400">
            {item.user.role}
          </span>
        </div>
      </div>
    ),
  },
  {
    title: "주소",
    key: "projectName",
  },
  {
    title: "담당자",
    key: "team",
    renderItem: (item: any) => (
      <div className="flex -space-x-2">
        {item.team.images.map((img: string, idx: number) => (
          <div
            key={idx}
            className="w-6 h-6 overflow-hidden border-2 border-white rounded-full dark:border-gray-900"
          >
            <Image
              width={24}
              height={24}
              src={img}
              alt={`Team member ${idx + 1}`}
              className="w-full h-full object-cover"
            />
          </div>
        ))}
      </div>
    ),
  },
  {
    title: "무인기기 상태",
    key: "status",
    renderItem: (item: any) => (
      <Badge
        size="sm"
        color={
          item.status === "정상"
            ? "success"
            : item.status === "장애"
              ? "error"
              : "warning"
        }
      >
        {item.status}
      </Badge>
    ),
  },
    {
    title: "수정",
    key: "actions",
    renderItem: (item: any, row: number) => (
      <button
        onClick={(e) => {
          e.stopPropagation();
          handleClickRow(item, row);
        }}
        className="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700"
      >
        수정
      </button>
    ),
  },
  {
    title: "판매량",
    key: "budget",
  },

];

//TempCode, 차후에 API로 불러오는 값
const tableData = [
  {
    user: {
      image: "/images/user/user-17.jpg",
      name: "롯데백화점",
      role: "신촌점",
    },
    projectName: "강남구 신사동",
    team: {
      images: [
        "/images/user/user-22.jpg",
        "/images/user/user-23.jpg",
        "/images/user/user-24.jpg",
      ],
    },
    budget: "3.9K",
    status: "정상",
  },
  {
    user: {
      image: "/images/user/user-18.jpg",
      name: "코엑스",
      role: "일산점",
    },
    projectName: "구로구 금천동",
    team: {
      images: ["/images/user/user-25.jpg", "/images/user/user-26.jpg"],
    },
    budget: "24.9K",
    status: "장애",
  },
  {
    user: {
      image: "/images/user/user-18.jpg",
      name: "스타필드",
      role: "하남점",
    },
    projectName: "고양시 덕양구",
    team: {
      images: ["/images/user/user-25.jpg", "/images/user/user-26.jpg"],
    },
    budget: "24.9K",
    status: "정상",
  },
];
//

export default function TempView() {
  const [ tableOffset, setTableOffset ] = useState<number>(0);
  const [ tableTotalCount, setTableTotalCount ] = useState<number>(0);

  //useEffect(() => {
  //  api.get('/api-test')
  //    .then((resp) => {
  //      console.log(resp)
  //    })
  //    .catch((err) => console.error(err));
  //}, []);


  const [searchFilters, setSearchFilters] = useState({
    user: "",
    projectName: "",
    team: "",
    status: "",
    budgetMin: "",
    budgetMax: "",
  });

  const handleChange = (key: string, value: string) => {
    setSearchFilters((prev) => ({ ...prev, [key]: value }));
  };

  const handleSearch = () => {
    console.log("검색 조건:", searchFilters);
  };


  const handleClickTableRow = (index: number) => {
    alert(index)
  };

  const handleClickTableCell = (rowIndex: number, colIndex: number, cellData: any) => {
    console.log(`셀 클릭됨 → row: ${rowIndex}, col: ${colIndex}, 데이터:`, cellData);
  };
  return (
    <div>
      <PageBreadcrumb pageTitle1="영업관리" pageTitle2="발주관리" />

      <div className="space-y-6">
        <ComponentCard2 title="거래처 목록">
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">
                  대리점
                </label>
                <input
                  type="text"
                  value={searchFilters.user}
                  onChange={(e) => handleChange("user", e.target.value)}
                  className="w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                />
              </div>
              <div className="md:col-span-3">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">
                  주소
                </label>
                <input
                  type="text"
                  value={searchFilters.projectName}
                  onChange={(e) => handleChange("projectName", e.target.value)}
                  className="w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">
                  담당자
                </label>
                <input
                  type="text"
                  value={searchFilters.team}
                  onChange={(e) => handleChange("team", e.target.value)}
                  className="w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">
                  무인기기 상태
                </label>
                <select
                  className="w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                  value={searchFilters.status}
                  onChange={(e) => handleChange("status", e.target.value)}
                >
                  <option value="">전체</option>
                  <option value="정상">정상</option>
                  <option value="장애">장애</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-400 mb-1">
                  판매량 (0 ~ 100k)
                </label>
                <div className="flex items-center gap-2 min-w-[280px]">
                  <input
                    type="number"
                    min={0}
                    max={100000}
                    placeholder="최소"
                    value={searchFilters.budgetMin}
                    onChange={(e) => handleChange("budgetMin", e.target.value)}
                    className="flex-1 rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                  />
                  <span className="text-gray-500">~</span>
                  <input
                    type="number"
                    min={0}
                    max={100000}
                    placeholder="최대"
                    value={searchFilters.budgetMax}
                    onChange={(e) => handleChange("budgetMax", e.target.value)}
                    className="flex-1 rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                  />
                </div>
              </div>
              <div className="flex justify-end">
                <button
                  onClick={handleSearch}
                  className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                >
                  검색
                </button>
              </div>
            </div>
          </div>


          {/* 테이블 */}
          <CtTable1
            columns={headerColumns}
            bodyData={tableData}
            offset={tableOffset} totalCount={tableTotalCount}
                countPerPage={COUNT_PER_PAGE} pageNumCount={PAGE_NUM_COUNT}
            // onClickRow={handleClickTableRow}
            onClickCell={handleClickTableCell}
            hoverRowClassName="hover:bg-blue-50 dark:hover:bg-blue-900/20"
            // hoverCellClassName="hover:bg-yellow-50 dark:hover:bg-yellow-900/10" 
          />
        </ComponentCard2>
      </div>
    </div>
  );
}
