import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Plus, Edit, Trash2, FileText, CheckCircle, XCircle } from "lucide-react";
import { useData } from "./contexts/DataContext";
import type { LotNumberRule } from "./contexts/DataContext";
import { LOTRuleForm } from "./LOTRuleForm";
import { MobileCard } from "./organisms/MobileCard";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";

export function LOTNumberManagement() {
  const { lotNumberRules, deleteLotNumberRule, generateLotNumber } = useData();
  const [showForm, setShowForm] = useState(false);
  const [editingRuleId, setEditingRuleId] = useState<string | undefined>(undefined);

  const handleOpenForm = (ruleId?: string) => {
    setEditingRuleId(ruleId);
    setShowForm(true);
  };

  const handleDelete = (id: string) => {
    if (confirm('정말 삭제하시겠습니까?')) {
      deleteLotNumberRule(id);
    }
  };

  const handleTestGenerate = (documentType: 'quote' | 'salesOrder' | 'production' | 'shipping' | 'purchase') => {
    const lotNumber = generateLotNumber(documentType);
    alert(`생성된 번호: ${lotNumber}`);
  };

  // 적용 대상 레이블 변환
  const getApplyToLabel = (applyTo: string[] | undefined) => {
    if (!applyTo || applyTo.length === 0) {
      return '-';
    }
    const labels: { [key: string]: string } = {
      quote: '견적',
      salesOrder: '수주',
      production: '생산지시',
      shipping: '출하지시',
      purchase: '발주',
    };
    return applyTo.map(v => labels[v] || v).join(', ');
  };

  // 페이지 전환 조건부 렌더링
  if (showForm) {
    return (
      <LOTRuleForm
        ruleId={editingRuleId}
        onBack={() => {
          setShowForm(false);
          setEditingRuleId(undefined);
        }}
      />
    );
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-gray-900">번호기준 관리</h1>
          <p className="text-sm text-gray-500 mt-1">
            견적서, 수주서, 생산지시서 등의 문서 번호 생성 규칙을 관리합니다.
          </p>
        </div>
        <Button onClick={() => handleOpenForm()}>
          <Plus className="h-4 w-4 mr-2" />
          규칙 추가
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>번호기준 규칙 목록</CardTitle>
        </CardHeader>
        <CardContent>
          {/* 데스크톱 테이블 뷰 */}
          <div className="hidden lg:block">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-16 text-center">번호</TableHead>
                  <TableHead>번호기준 이름</TableHead>
                  <TableHead>적용 대상</TableHead>
                  <TableHead>접두사</TableHead>
                  <TableHead>날짜 형식</TableHead>
                  <TableHead>순번 자릿수</TableHead>
                  <TableHead>구분자</TableHead>
                  <TableHead>예시</TableHead>
                  <TableHead>상태</TableHead>
                  <TableHead>작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {lotNumberRules.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={10} className="text-center text-gray-500 py-8">
                      등록된 번호기준 규칙이 없습니다.
                    </TableCell>
                  </TableRow>
                ) : (
                  // 내림차순 정렬: 최신 등록이 맨 위
                  [...lotNumberRules]
                    .sort((a, b) => {
                      const dateA = new Date(a.createdAt || 0).getTime();
                      const dateB = new Date(b.createdAt || 0).getTime();
                      return dateB - dateA;
                    })
                    .map((rule, index) => (
                    <TableRow key={rule.id}>
                      <TableCell className="text-center text-muted-foreground">{index + 1}</TableCell>
                      <TableCell>{rule.ruleName}</TableCell>
                      <TableCell>{getApplyToLabel(rule.applyTo)}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{rule.prefix}</Badge>
                      </TableCell>
                      <TableCell>
                        {rule.useDate ? rule.dateFormat : '사용 안 함'}
                      </TableCell>
                      <TableCell className="text-center">{rule.sequenceDigits}자리</TableCell>
                      <TableCell className="text-center">{rule.separator}</TableCell>
                      <TableCell>
                        <code className="text-sm bg-gray-100 px-2 py-1 rounded">
                          {rule.example}
                        </code>
                      </TableCell>
                      <TableCell>
                        {rule.isActive ? (
                          <Badge className="bg-green-500">
                            <CheckCircle className="h-3 w-3 mr-1" />
                            활성
                          </Badge>
                        ) : (
                          <Badge variant="secondary">
                            <XCircle className="h-3 w-3 mr-1" />
                            비활성
                          </Badge>
                        )}
                      </TableCell>
                      <TableCell>
                        <div className="flex gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => rule.applyTo && rule.applyTo.length > 0 && handleTestGenerate(rule.applyTo[0])}
                            disabled={!rule.applyTo || rule.applyTo.length === 0}
                          >
                            <FileText className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleOpenForm(rule.id)}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDelete(rule.id)}
                          >
                            <Trash2 className="h-4 w-4 text-red-500" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          {/* 태블릿/모바일 카드 뷰 */}
          <div className="lg:hidden space-y-3">
            {lotNumberRules.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <FileText className="w-12 h-12 mx-auto mb-3 text-muted-foreground" />
                <p>등록된 번호기준 규칙이 없습니다.</p>
              </div>
            ) : (
              [...lotNumberRules]
                .sort((a, b) => {
                  const dateA = new Date(a.createdAt || 0).getTime();
                  const dateB = new Date(b.createdAt || 0).getTime();
                  return dateB - dateA;
                })
                .map((rule, index) => {
                  const fields = [
                    { label: "적용 대상", value: getApplyToLabel(rule.applyTo) },
                    { label: "접두사", value: rule.prefix, badge: true },
                    { label: "날짜 형식", value: rule.useDate ? rule.dateFormat : '사용 안 함' },
                    { label: "순번 자릿수", value: `${rule.sequenceDigits}자리` },
                    { label: "구분자", value: rule.separator },
                    { label: "예시", value: rule.example },
                  ];

                  if (rule.description) {
                    fields.push({ label: "설명", value: rule.description });
                  }

                  const actions = [
                    {
                      label: "테스트",
                      icon: FileText,
                      variant: "outline" as const,
                      onClick: () => rule.applyTo && rule.applyTo.length > 0 && handleTestGenerate(rule.applyTo[0]),
                      disabled: !rule.applyTo || rule.applyTo.length === 0,
                    },
                    {
                      label: "수정",
                      icon: Edit,
                      variant: "outline" as const,
                      onClick: () => handleOpenForm(rule.id),
                    },
                    {
                      label: "삭제",
                      icon: Trash2,
                      variant: "outline" as const,
                      onClick: () => handleDelete(rule.id),
                    },
                  ];

                  return (
                    <MobileCard
                      key={rule.id}
                      icon={<FileText className="w-5 h-5 text-blue-600" />}
                      title={rule.ruleName}
                      subtitle={`#${index + 1}`}
                      badge={
                        rule.isActive
                          ? { label: "활성", variant: "default" }
                          : { label: "비활성", variant: "secondary" }
                      }
                      fields={fields}
                      actions={actions}
                    />
                  );
                })
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}