/**
 * 번호기준 규칙 등록/수정 페이지
 * 디자인 시스템 템플릿 적용
 */

import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Checkbox } from "./ui/checkbox";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { ArrowLeft, FileText, Save } from "lucide-react";
import { useData } from "./contexts/DataContext";
import type { LotNumberRule } from "./contexts/DataContext";
import { toast } from "sonner@2.0.3";

interface LOTRuleFormProps {
  ruleId?: string; // 수정 시 규칙 ID
  onBack: () => void;
}

export function LOTRuleForm({ ruleId, onBack }: LOTRuleFormProps) {
  const { lotNumberRules, addLotNumberRule, updateLotNumberRule } = useData();
  const editingRule = ruleId ? lotNumberRules.find(r => r.id === ruleId) : null;
  
  const [formData, setFormData] = useState<Partial<LotNumberRule>>({
    ruleName: '',
    applyTo: [],
    prefix: 'KD',
    useDate: true,
    dateFormat: 'YYMMDD',
    sequenceDigits: 2,
    separator: '-',
    description: '',
    isActive: true,
  });

  // 수정 모드일 경우 데이터 로드
  useEffect(() => {
    if (editingRule) {
      setFormData(editingRule);
    }
  }, [editingRule]);

  const applyToOptions = [
    { value: 'quote', label: '견적번호' },
    { value: 'salesOrder', label: '수주번호' },
    { value: 'production', label: '생산지시번호' },
    { value: 'shipping', label: '출하지시번호' },
    { value: 'purchase', label: '발주번호' },
  ];

  const dateFormatOptions = [
    { value: 'YYMMDD', label: 'YYMMDD (251119)' },
    { value: 'YYYYMMDD', label: 'YYYYMMDD (20251119)' },
    { value: 'YYMM', label: 'YYMM (2511)' },
    { value: 'YYYYMM', label: 'YYYYMM (202511)' },
  ];

  // 적용 대상 토글
  const handleApplyToToggle = (value: string) => {
    const currentApplyTo = formData.applyTo || [];
    if (currentApplyTo.includes(value as any)) {
      setFormData({
        ...formData,
        applyTo: currentApplyTo.filter(v => v !== value) as any,
      });
    } else {
      setFormData({
        ...formData,
        applyTo: [...currentApplyTo, value] as any,
      });
    }
  };

  // 예시 번호 생성
  const generateExample = () => {
    const today = new Date();
    const yyyy = String(today.getFullYear());
    const yy = String(today.getFullYear()).slice(-2);
    const mm = String(today.getMonth() + 1).padStart(2, '0');
    const dd = String(today.getDate()).padStart(2, '0');
    
    let dateStr = '';
    if (formData.useDate) {
      switch (formData.dateFormat) {
        case 'YYMMDD':
          dateStr = `${yy}${mm}${dd}`;
          break;
        case 'YYYYMMDD':
          dateStr = `${yyyy}${mm}${dd}`;
          break;
        case 'YYMM':
          dateStr = `${yy}${mm}`;
          break;
        case 'YYYYMM':
          dateStr = `${yyyy}${mm}`;
          break;
      }
    }
    
    const separator = formData.separator === '없음' ? '' : (formData.separator || '-');
    const sequenceExample = '1'.padStart(formData.sequenceDigits || 2, '0');
    
    let example = formData.prefix || 'PREFIX';
    if (dateStr) {
      example += `${separator}${dateStr}`;
    }
    example += `${separator}${sequenceExample}`;
    
    return example;
  };

  const handleSave = () => {
    if (!formData.ruleName || !formData.prefix) {
      toast.error('번호기준 이름과 접두사는 필수입니다.');
      return;
    }

    if (!formData.applyTo || formData.applyTo.length === 0) {
      toast.error('적어도 하나의 적용 대상을 선택해주세요.');
      return;
    }

    const example = generateExample();

    if (editingRule) {
      // 수정
      updateLotNumberRule(editingRule.id, {
        ...formData,
        example,
        updatedAt: new Date().toISOString(),
      });
      toast.success('번호기준 규칙이 수정되었습니다.');
    } else {
      // 신규 추가
      const newRule: LotNumberRule = {
        id: `lot-rule-${Date.now()}`,
        ruleName: formData.ruleName || '',
        applyTo: formData.applyTo || [],
        prefix: formData.prefix || '',
        useDate: formData.useDate || false,
        dateFormat: formData.dateFormat || 'YYMMDD',
        sequenceDigits: formData.sequenceDigits || 2,
        separator: formData.separator || '-',
        example,
        description: formData.description,
        isActive: formData.isActive || true,
        createdAt: new Date().toISOString(),
      };
      addLotNumberRule(newRule);
      toast.success('번호기준 규칙이 추가되었습니다.');
    }

    onBack();
  };

  return (
    <PageLayout>
      <PageHeader
        title={editingRule ? '번호기준 규칙 수정' : '번호기준 규칙 추가'}
        icon={FileText}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={onBack}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              목록으로
            </Button>
            <Button onClick={handleSave}>
              <Save className="w-4 h-4 mr-2" />
              {editingRule ? '수정' : '저장'}
            </Button>
          </div>
        }
      />

      <div className="space-y-6">
        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle>기본 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div>
                <Label>번호기준 이름 *</Label>
                <Input
                  className="mt-2"
                  value={formData.ruleName || ''}
                  onChange={(e) =>
                    setFormData({ ...formData, ruleName: e.target.value })
                  }
                  placeholder="예: 견적번호 기준, 표준 문서번호 기준"
                />
                <p className="text-sm text-muted-foreground mt-1">
                  이 번호기준을 구분할 수 있는 이름을 입력하세요
                </p>
              </div>

              <div>
                <Label>적용 대상 * (복수 선택 가능)</Label>
                <div className="mt-3 space-y-3">
                  {applyToOptions.map((option) => (
                    <div key={option.value} className="flex items-center space-x-2">
                      <Checkbox
                        id={option.value}
                        checked={(formData.applyTo || []).includes(option.value as any)}
                        onCheckedChange={() => handleApplyToToggle(option.value)}
                      />
                      <label
                        htmlFor={option.value}
                        className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
                      >
                        {option.label}
                      </label>
                    </div>
                  ))}
                </div>
                <p className="text-sm text-muted-foreground mt-2">
                  이 번호기준이 적용될 문서를 선택하세요
                </p>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label>접두사 *</Label>
                  <Input
                    className="mt-2"
                    value={formData.prefix || ''}
                    onChange={(e) =>
                      setFormData({ ...formData, prefix: e.target.value })
                    }
                    placeholder="예: KD, PR, SO"
                  />
                  <p className="text-sm text-muted-foreground mt-1">
                    번호 앞에 붙을 고정 문자열
                  </p>
                </div>

                <div>
                  <Label>구분자 *</Label>
                  <Select
                    value={formData.separator || '-'}
                    onValueChange={(value) =>
                      setFormData({ ...formData, separator: value })
                    }
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="-">하이픈 (-)</SelectItem>
                      <SelectItem value="_">언더스코어 (_)</SelectItem>
                      <SelectItem value="없음">없음</SelectItem>
                    </SelectContent>
                  </Select>
                  <p className="text-sm text-muted-foreground mt-1">
                    각 요소 사이에 들어갈 구분 문자
                  </p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 날짜 및 순번 설정 */}
        <Card>
          <CardHeader>
            <CardTitle>날짜 및 순번 설정</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label>날짜 사용</Label>
                  <Select
                    value={formData.useDate ? 'true' : 'false'}
                    onValueChange={(value) =>
                      setFormData({ ...formData, useDate: value === 'true' })
                    }
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="true">사용</SelectItem>
                      <SelectItem value="false">사용 안 함</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label>날짜 형식</Label>
                  <Select
                    value={formData.dateFormat || 'YYMMDD'}
                    onValueChange={(value: any) =>
                      setFormData({ ...formData, dateFormat: value })
                    }
                    disabled={!formData.useDate}
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {dateFormatOptions.map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label>순번 자릿수 *</Label>
                  <Select
                    value={String(formData.sequenceDigits)}
                    onValueChange={(value) =>
                      setFormData({ ...formData, sequenceDigits: parseInt(value) })
                    }
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="2">2자리 (01~99)</SelectItem>
                      <SelectItem value="3">3자리 (001~999)</SelectItem>
                      <SelectItem value="4">4자리 (0001~9999)</SelectItem>
                    </SelectContent>
                  </Select>
                  <p className="text-sm text-muted-foreground mt-1">
                    일련번호 자릿수 (0으로 채워짐)
                  </p>
                </div>

                <div>
                  <Label>상태</Label>
                  <Select
                    value={formData.isActive ? 'true' : 'false'}
                    onValueChange={(value) =>
                      setFormData({ ...formData, isActive: value === 'true' })
                    }
                  >
                    <SelectTrigger className="mt-2">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="true">활성</SelectItem>
                      <SelectItem value="false">비활성</SelectItem>
                    </SelectContent>
                  </Select>
                  <p className="text-sm text-muted-foreground mt-1">
                    비활성 시 번호 생성에 사용되지 않음
                  </p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 설명 및 미리보기 */}
        <Card>
          <CardHeader>
            <CardTitle>추가 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div>
                <Label>설명</Label>
                <Input
                  className="mt-2"
                  value={formData.description || ''}
                  onChange={(e) =>
                    setFormData({ ...formData, description: e.target.value })
                  }
                  placeholder="규칙에 대한 설명을 입력하세요"
                />
              </div>

              <div className="bg-blue-50 border border-blue-200 rounded-lg p-6">
                <div className="flex items-center gap-2 mb-3">
                  <FileText className="h-5 w-5 text-blue-600" />
                  <span className="text-sm text-blue-900">생성 번호 미리보기</span>
                </div>
                <code className="text-2xl bg-white px-6 py-4 rounded border border-blue-200 block text-center text-blue-900 font-mono">
                  {generateExample()}
                </code>
                <p className="text-xs text-blue-700 mt-2 text-center">
                  * 실제 생성 시 일련번호는 자동으로 증가합니다
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </PageLayout>
  );
}