"use client";

import React, { useState } from 'react';
import { ChevronDown, ChevronUp, MapPin, Check } from 'lucide-react';
import { RouteItem } from '../types';
import { cn } from '@/lib/utils';

interface RouteListProps {
  routes: RouteItem[];
  selectedId: string | null;
  onSelect: (route: RouteItem) => void;
  onToggleItem: (routeId: string, itemId: string, isCompleted: boolean) => void;
  reportCode: string | null;
  isMock?: boolean;
}

export const RouteList = ({ routes, selectedId, onSelect, onToggleItem, reportCode, isMock }: RouteListProps) => {
  const [expandedId, setExpandedId] = useState<string | null>(null);

  const handleClick = (route: RouteItem) => {
    onSelect(route);
    setExpandedId(expandedId === route.id ? null : route.id);
  };

  const handleToggle = (e: React.MouseEvent, routeId: string, itemId: string, currentState: boolean) => {
    e.stopPropagation();
    onToggleItem(routeId, itemId, !currentState);
  };

  return (
    <div className="bg-white rounded-lg p-3 sm:p-4 shadow-sm h-full flex flex-col overflow-hidden">
      <div className="flex items-center gap-2 mb-3 sm:mb-4">
        <h2 className="font-bold text-gray-800 text-xs sm:text-sm">
          수주로트 목록{' '}
          {reportCode && (
            <span className="text-gray-400 font-normal ml-1">({reportCode})</span>
          )}
        </h2>
        {isMock && (
          <span className="bg-amber-100 text-amber-700 text-[9px] sm:text-[10px] font-semibold px-1.5 py-0.5 rounded border border-amber-200">
            Mock
          </span>
        )}
      </div>

      <div className="space-y-2 sm:space-y-3 overflow-y-auto flex-1">
        {routes.length === 0 ? (
          <div className="flex items-center justify-center h-32 text-gray-400 text-sm">
            {reportCode ? '수주로트가 없습니다.' : '품질관리서를 선택해주세요.'}
          </div>
        ) : (
          routes.map((route) => {
            const isSelected = selectedId === route.id;
            const isExpanded = expandedId === route.id;
            const completedCount = route.subItems.filter(item => item.isCompleted).length;
            const totalCount = route.subItems.length;

            return (
              <div key={route.id} className="border border-gray-200 rounded-lg overflow-hidden">
                <div
                  onClick={() => handleClick(route)}
                  className={`p-3 sm:p-4 cursor-pointer flex justify-between items-start transition-colors ${
                    isSelected ? 'bg-green-50 border-b border-green-100' : 'bg-white hover:bg-gray-50'
                  }`}
                >
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      {isSelected && <div className="w-1 h-4 bg-green-500 rounded-full" />}
                      <h3 className={`font-bold ${isSelected ? 'text-green-700' : 'text-gray-700'}`}>
                        {route.code}
                      </h3>
                      {totalCount > 0 && (
                        <span className={cn(
                          'text-[10px] font-medium px-1.5 py-0.5 rounded',
                          completedCount === totalCount
                            ? 'bg-green-100 text-green-700'
                            : 'bg-gray-100 text-gray-600'
                        )}>
                          {completedCount}/{totalCount}
                        </span>
                      )}
                    </div>
                    <p className="text-xs text-gray-500 mb-0.5">수주일: {route.date || '-'}</p>
                    <p className="text-xs text-gray-500 mb-2">현장: {route.site || '-'}{route.client ? ` (${route.client})` : ''}</p>
                    <div className="inline-flex items-center gap-1 bg-gray-100 px-2 py-0.5 rounded text-xs text-gray-600">
                      <MapPin size={10} />
                      <span>{route.locationCount}개소</span>
                    </div>
                  </div>
                  {isExpanded ? (
                    <ChevronUp size={16} className="text-gray-400" />
                  ) : (
                    <ChevronDown size={16} className="text-gray-400" />
                  )}
                </div>

                {isExpanded && route.subItems.length > 0 && (
                  <div className="bg-white p-2 sm:p-3 space-y-1.5 sm:space-y-2">
                    <div className="text-xs font-bold text-gray-600 mb-1.5 sm:mb-2 flex items-center gap-1">
                      <MapPin size={10} /> 개소별 제품로트
                    </div>
                    {route.subItems.map((item) => (
                      <div
                        key={item.id}
                        className={cn(
                          "flex items-center justify-between border p-2 rounded transition-colors",
                          item.isCompleted
                            ? "border-green-200 bg-green-50"
                            : "border-gray-100 hover:bg-gray-50"
                        )}
                      >
                        <div className="flex-1">
                          <div className={cn(
                            "text-xs font-bold",
                            item.isCompleted ? "text-green-700" : "text-gray-700"
                          )}>
                            {item.name}
                          </div>
                          <div className="text-xs text-gray-500">{item.location}</div>
                        </div>
                        <button
                          type="button"
                          onClick={(e) => handleToggle(e, route.id, item.id, item.isCompleted)}
                          className={cn(
                            "flex items-center gap-1 text-[10px] font-bold px-2 py-1 rounded border transition-all",
                            item.isCompleted
                              ? "text-green-600 border-green-300 bg-green-100 hover:bg-green-200"
                              : "text-gray-500 border-gray-300 bg-white hover:bg-blue-50 hover:text-blue-600 hover:border-blue-300"
                          )}
                        >
                          <Check size={12} className={item.isCompleted ? "text-green-600" : "text-gray-400"} />
                          {item.isCompleted ? '완료' : '확인'}
                        </button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            );
          })
        )}
      </div>
    </div>
  );
};