import { ReactNode, useState } from "react";
import { LucideIcon } from "lucide-react";
import { PageLayout } from "../organisms/PageLayout";
import { PageHeader } from "../organisms/PageHeader";
import { SearchFilter } from "../organisms/SearchFilter";
import { StatCards } from "../organisms/StatCards";
import { DataTable, Column } from "../organisms/DataTable";
import { EmptyState } from "../organisms/EmptyState";
import { MobileCard } from "../organisms/MobileCard";
import { FormActions } from "../organisms/FormActions";
import { DetailViewActions } from "../organisms/DetailViewActions";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";

/**
 * CRUD Page Template
 * 
 * 품목관리 패턴을 기반으로 한 범용 CRUD 페이지 템플릿
 * List → Create/Edit → View 플로우를 표준화
 * 
 * @example
 * ```tsx
 * <CRUDPageTemplate
 *   title="거래처 관리"
 *   data={clients}
 *   columns={columns}
 *   renderForm={(data, onChange) => <ClientForm data={data} onChange={onChange} />}
 *   onSave={handleSave}
 *   onDelete={handleDelete}
 * />
 * ```
 */

export interface CRUDPageTemplateProps<T extends { id: string }> {
  // ===== 기본 정보 =====
  title: string;
  description?: string;
  icon?: LucideIcon;
  
  // ===== 데이터 =====
  data: T[];
  keyField?: keyof T;
  
  // ===== 목록 화면 (List View) =====
  columns: Column<T>[];
  stats?: Array<{
    label: string;
    value: string | number;
    icon: LucideIcon;
    iconColor?: string;
    trend?: { value: string; isPositive: boolean };
  }>;
  
  // 검색 & 필터
  searchPlaceholder?: string;
  searchFields?: (keyof T)[]; // 검색할 필드들
  filterComponent?: ReactNode; // 커스텀 필터 UI
  
  // 모바일 카드 렌더링
  renderMobileCard?: (item: T) => {
    title: string;
    subtitle?: string;
    icon?: ReactNode;
    badge?: { label: string; variant?: "default" | "secondary" | "destructive" | "outline" };
    fields: Array<{ label: string; value: string }>;
    actions?: ReactNode;
  };
  
  // Empty State
  emptyIcon?: LucideIcon;
  emptyTitle?: string;
  emptyDescription?: string;
  
  // ===== 등록/수정 화면 (Form View) =====
  renderForm: (
    formData: Partial<T> | null,
    onChange: (field: keyof T, value: any) => void,
    errors?: Record<string, string>
  ) => ReactNode;
  
  // 폼 검증
  validateForm?: (data: Partial<T>) => Record<string, string> | null;
  
  // 초기값 생성
  getDefaultFormData?: () => Partial<T>;
  
  // ===== 상세 화면 (Detail View) =====
  renderDetail?: (item: T) => ReactNode;
  
  // 탭 구성 (상세 화면에서 사용)
  detailTabs?: Array<{
    id: string;
    label: string;
    icon?: LucideIcon;
    render: (item: T) => ReactNode;
  }>;
  
  // ===== 액션 =====
  onCreate?: (data: Partial<T>) => void | Promise<void>;
  onUpdate?: (id: string, data: Partial<T>) => void | Promise<void>;
  onDelete?: (id: string) => void | Promise<void>;
  onView?: (item: T) => void; // 커스텀 상세보기 동작
  
  // 추가 액션 버튼
  customActions?: Array<{
    label: string;
    icon?: LucideIcon;
    onClick: () => void;
    variant?: "default" | "outline" | "destructive";
  }>;
  
  // 행별 액션
  rowActions?: (item: T) => Array<{
    label: string;
    icon?: LucideIcon;
    onClick: () => void;
    variant?: "default" | "outline" | "destructive";
  }>;
  
  // ===== 옵션 =====
  enableCreate?: boolean; // 등록 기능 활성화 (기본: true)
  enableEdit?: boolean; // 수정 기능 활성화 (기본: true)
  enableDelete?: boolean; // 삭제 기능 활성화 (기본: true)
  enableView?: boolean; // 상세보기 기능 활성화 (기본: true)
  enableSearch?: boolean; // 검색 기능 활성화 (기본: true)
  enableStats?: boolean; // 통계 카드 활성화 (기본: true)
  
  // 페이지네이션
  pagination?: {
    currentPage: number;
    totalPages: number;
    pageSize: number;
    onPageChange: (page: number) => void;
  };
  
  // 로딩 상태
  loading?: boolean;
  
  // 개발자 모드
  devMode?: boolean;
}

type ViewMode = "list" | "create" | "edit" | "view";

export function CRUDPageTemplate<T extends { id: string }>(props: CRUDPageTemplateProps<T>) {
  const {
    title,
    description,
    icon,
    data,
    keyField = "id" as keyof T,
    columns,
    stats,
    searchPlaceholder = `${title} 검색...`,
    searchFields,
    filterComponent,
    renderMobileCard,
    emptyIcon,
    emptyTitle,
    emptyDescription,
    renderForm,
    validateForm,
    getDefaultFormData,
    renderDetail,
    detailTabs,
    onCreate,
    onUpdate,
    onDelete,
    onView,
    customActions,
    rowActions,
    enableCreate = true,
    enableEdit = true,
    enableDelete = true,
    enableView = true,
    enableSearch = true,
    enableStats = true,
    pagination,
    loading = false,
    devMode = false,
  } = props;
  
  // ===== State =====
  const [viewMode, setViewMode] = useState<ViewMode>("list");
  const [selectedItem, setSelectedItem] = useState<T | null>(null);
  const [formData, setFormData] = useState<Partial<T> | null>(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [errors, setErrors] = useState<Record<string, string>>({});
  
  // ===== 검색 & 필터링 =====
  const filteredData = searchTerm && searchFields
    ? data.filter(item => {
        const searchLower = searchTerm.toLowerCase();
        return searchFields.some(field => {
          const value = item[field];
          return String(value).toLowerCase().includes(searchLower);
        });
      })
    : data;
  
  // ===== 액션 핸들러 =====
  const handleCreate = () => {
    setViewMode("create");
    setFormData(getDefaultFormData?.() || {});
    setErrors({});
  };
  
  const handleEdit = (item: T) => {
    setViewMode("edit");
    setSelectedItem(item);
    setFormData({ ...item });
    setErrors({});
  };
  
  const handleView = (item: T) => {
    if (onView) {
      onView(item);
    } else if (enableView) {
      setViewMode("view");
      setSelectedItem(item);
    }
  };
  
  const handleSave = async () => {
    if (!formData) return;
    
    // 검증
    if (validateForm) {
      const validationErrors = validateForm(formData);
      if (validationErrors && Object.keys(validationErrors).length > 0) {
        setErrors(validationErrors);
        return;
      }
    }
    
    try {
      if (viewMode === "create" && onCreate) {
        await onCreate(formData);
      } else if (viewMode === "edit" && onUpdate && selectedItem) {
        await onUpdate(selectedItem.id, formData);
      }
      
      // 성공 시 목록으로 이동
      setViewMode("list");
      setFormData(null);
      setSelectedItem(null);
      setErrors({});
    } catch (error) {
      console.error("Save failed:", error);
    }
  };
  
  const handleCancel = () => {
    setViewMode("list");
    setFormData(null);
    setSelectedItem(null);
    setErrors({});
  };
  
  const handleDelete = async (item: T) => {
    if (!onDelete) return;
    if (!confirm(`정말 삭제하시겠습니까?`)) return;
    
    try {
      await onDelete(item.id);
    } catch (error) {
      console.error("Delete failed:", error);
    }
  };
  
  const handleFormChange = (field: keyof T, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // 해당 필드의 에러 제거
    if (errors[field as string]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field as string];
        return newErrors;
      });
    }
  };
  
  // ===== 목록 화면 액션 =====
  const enhancedColumns: Column<T>[] = [
    ...columns,
    ...(enableEdit || enableDelete || rowActions
      ? [{
          key: "_actions" as keyof T,
          label: "관리",
          render: (item: T) => (
            <div className="flex gap-2 justify-end">
              {enableView && (
                <button
                  onClick={() => handleView(item)}
                  className="text-blue-600 hover:text-blue-800"
                >
                  보기
                </button>
              )}
              {enableEdit && (
                <button
                  onClick={() => handleEdit(item)}
                  className="text-green-600 hover:text-green-800"
                >
                  수정
                </button>
              )}
              {enableDelete && (
                <button
                  onClick={() => handleDelete(item)}
                  className="text-red-600 hover:text-red-800"
                >
                  삭제
                </button>
              )}
              {rowActions?.(item).map((action, idx) => (
                <button
                  key={idx}
                  onClick={action.onClick}
                  className="text-gray-600 hover:text-gray-800"
                >
                  {action.label}
                </button>
              ))}
            </div>
          ),
        }]
      : []),
  ];
  
  // ===== 렌더링 =====
  
  // 목록 화면
  if (viewMode === "list") {
    return (
      <PageLayout>
        <PageHeader
          title={title}
          description={description}
          icon={icon}
          actions={
            <div className="flex gap-2">
              {customActions?.map((action, idx) => (
                <button
                  key={idx}
                  onClick={action.onClick}
                  className="px-4 py-2 bg-gray-100 rounded hover:bg-gray-200"
                >
                  {action.icon && <action.icon className="w-4 h-4 mr-2 inline" />}
                  {action.label}
                </button>
              ))}
              {enableCreate && (
                <button
                  onClick={handleCreate}
                  className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                >
                  새로 만들기
                </button>
              )}
            </div>
          }
        />
        
        {enableStats && stats && <StatCards stats={stats} />}
        
        {enableSearch && (
          <SearchFilter
            searchValue={searchTerm}
            onSearchChange={setSearchTerm}
            searchPlaceholder={searchPlaceholder}
            extraActions={filterComponent}
          />
        )}
        
        {filteredData.length === 0 ? (
          <EmptyState
            icon={emptyIcon || icon}
            title={emptyTitle || `${title} 데이터가 없습니다`}
            description={emptyDescription}
            action={
              enableCreate
                ? {
                    label: "새로 만들기",
                    onClick: handleCreate,
                  }
                : undefined
            }
          />
        ) : (
          <>
            <DataTable
              columns={enhancedColumns}
              data={filteredData}
              keyField={keyField}
              onRowClick={enableView ? handleView : undefined}
              loading={loading}
              pagination={pagination}
            />
            
            {renderMobileCard && (
              <div className="md:hidden space-y-3">
                {filteredData.map((item) => {
                  const cardProps = renderMobileCard(item);
                  return <MobileCard key={item.id} {...cardProps} />;
                })}
              </div>
            )}
          </>
        )}
      </PageLayout>
    );
  }
  
  // 등록/수정 화면
  if (viewMode === "create" || viewMode === "edit") {
    return (
      <PageLayout>
        <PageHeader
          title={viewMode === "create" ? `${title} 등록` : `${title} 수정`}
          description={viewMode === "create" ? `새로운 ${title}을 등록합니다` : `${title} 정보를 수정합니다`}
          icon={icon}
        />
        
        <Card>
          <CardHeader>
            <CardTitle>{viewMode === "create" ? "신규 등록" : "정보 수정"}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {renderForm(formData, handleFormChange, errors)}
          </CardContent>
        </Card>
        
        <FormActions
          onSave={handleSave}
          onCancel={handleCancel}
          saveLabel={viewMode === "create" ? "등록" : "저장"}
        />
      </PageLayout>
    );
  }
  
  // 상세보기 화면
  if (viewMode === "view" && selectedItem) {
    return (
      <PageLayout>
        <PageHeader
          title={`${title} 상세`}
          description={`${title} 상세 정보를 확인합니다`}
          icon={icon}
        />
        
        {detailTabs && detailTabs.length > 0 ? (
          <Tabs defaultValue={detailTabs[0].id}>
            <TabsList>
              {detailTabs.map(tab => (
                <TabsTrigger key={tab.id} value={tab.id}>
                  {tab.icon && <tab.icon className="w-4 h-4 mr-2" />}
                  {tab.label}
                </TabsTrigger>
              ))}
            </TabsList>
            {detailTabs.map(tab => (
              <TabsContent key={tab.id} value={tab.id}>
                <Card>
                  <CardContent className="pt-6">
                    {tab.render(selectedItem)}
                  </CardContent>
                </Card>
              </TabsContent>
            ))}
          </Tabs>
        ) : renderDetail ? (
          <Card>
            <CardContent className="pt-6">
              {renderDetail(selectedItem)}
            </CardContent>
          </Card>
        ) : (
          <Card>
            <CardContent className="pt-6">
              <pre>{JSON.stringify(selectedItem, null, 2)}</pre>
            </CardContent>
          </Card>
        )}
        
        <DetailViewActions
          onEdit={enableEdit ? () => handleEdit(selectedItem) : undefined}
          onDelete={enableDelete ? () => handleDelete(selectedItem) : undefined}
          onBack={handleCancel}
        />
      </PageLayout>
    );
  }
  
  return null;
}
