'use client';

/**
 * 수리이력 등록/수정 폼
 * URL: /quality/equipment-repairs?mode=new
 */

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Loader2, Save, X, Zap } from 'lucide-react';
import { toast } from 'sonner';
import { useMenuStore } from '@/stores/menuStore';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { FormField } from '@/components/molecules/FormField';
import { CurrencyInput } from '@/components/ui/currency-input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  createRepair,
  getEquipmentOptions,
  getManagerOptions,
} from '@/components/quality/EquipmentManagement/actions';
import type {
  RepairFormData,
  EquipmentOptions,
  ManagerOption,
} from '@/components/quality/EquipmentManagement/types';
import { REPAIR_TYPE_LABEL } from '@/components/quality/EquipmentManagement/types';

const initialFormData: RepairFormData = {
  equipmentId: '',
  repairDate: '',
  repairType: '',
  repairHours: '',
  description: '',
  cost: '',
  vendor: '',
  repairedBy: '',
  memo: '',
};

export function RepairForm() {
  const router = useRouter();
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);
  const listPath = '/quality/equipment-repairs';

  const [formData, setFormData] = useState<RepairFormData>(initialFormData);
  const [options, setOptions] = useState<EquipmentOptions | null>(null);
  const [managers, setManagers] = useState<ManagerOption[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    Promise.all([
      getEquipmentOptions(),
      getManagerOptions(),
    ]).then(([optResult, mgrResult]) => {
      if (optResult.success && optResult.data) {
        setOptions(optResult.data);
      }
      setManagers(mgrResult);
    });
  }, []);

  const handleChange = useCallback((field: keyof RepairFormData, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  }, []);

  const handleSubmit = useCallback(async () => {
    if (!formData.equipmentId) {
      toast.error('설비를 선택하세요.');
      return;
    }
    if (!formData.repairDate) {
      toast.error('수리일을 입력하세요.');
      return;
    }
    if (!formData.repairType) {
      toast.error('보전구분을 선택하세요.');
      return;
    }

    setIsSubmitting(true);
    try {
      const result = await createRepair(formData);
      if (result.success) {
        toast.success('수리이력이 등록되었습니다.');
        router.push(listPath);
      } else {
        toast.error(result.error || '등록에 실패했습니다.');
      }
    } finally {
      setIsSubmitting(false);
    }
  }, [formData, router, listPath]);

  return (
    <div className="space-y-6 p-3 md:p-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold flex items-center gap-1">
          수리이력 등록
          <Zap className="h-5 w-5 text-yellow-500" />
        </h1>
        <Button
          variant="link"
          className="text-muted-foreground"
          onClick={() => router.push(listPath)}
        >
          ← 목록으로
        </Button>
      </div>

      {/* 폼 */}
      <Card>
        <CardContent className="pt-6 space-y-6">
          {/* Row 1: 설비 | 수리일 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label>설비 <span className="text-red-500">*</span></Label>
              <div className="mt-1">
                <Select
                  value={formData.equipmentId || '_none'}
                  onValueChange={(v) => handleChange('equipmentId', v === '_none' ? '' : v)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="선택" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="_none">선택</SelectItem>
                    {(options?.equipmentList || []).map((eq) => (
                      <SelectItem key={eq.id} value={String(eq.id)}>
                        {eq.equipmentCode} {eq.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <FormField
              label="수리일"
              type="date"
              required
              value={formData.repairDate}
              onChange={(v) => handleChange('repairDate', v)}
            />
          </div>

          {/* Row 2: 보전구분 | 수리시간 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label>보전구분 <span className="text-red-500">*</span></Label>
              <div className="mt-1">
                <Select
                  value={formData.repairType || '_none'}
                  onValueChange={(v) => handleChange('repairType', v === '_none' ? '' : v)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="선택" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="_none">선택</SelectItem>
                    {Object.entries(REPAIR_TYPE_LABEL).map(([val, label]) => (
                      <SelectItem key={val} value={val}>
                        {label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <FormField
              label="수리시간 (h)"
              type="number"
              value={formData.repairHours}
              onChange={(v) => handleChange('repairHours', v)}
            />
          </div>

          {/* Row 3: 수리내용 */}
          <div>
            <Label>수리내용</Label>
            <div className="mt-1">
              <Textarea
                value={formData.description}
                onChange={(e) => handleChange('description', e.target.value)}
                placeholder="수리 내용을 입력하세요"
                rows={4}
              />
            </div>
          </div>

          {/* Row 4: 수리비용 | 외주업체 | 수리자 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="space-y-2">
              <Label className="text-sm font-medium">수리비용 (원)</Label>
              <CurrencyInput
                value={formData.cost ? Number(formData.cost) : undefined}
                onChange={(v) => handleChange('cost', v ? String(v) : '')}
                showCurrency={false}
              />
            </div>
            <FormField
              label="외주업체"
              value={formData.vendor}
              onChange={(v) => handleChange('vendor', v)}
            />
            <div>
              <Label>수리자</Label>
              <div className="mt-1">
                <Select
                  value={formData.repairedBy || '_none'}
                  onValueChange={(v) => handleChange('repairedBy', v === '_none' ? '' : v)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="선택" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="_none">선택</SelectItem>
                    {managers.map((m) => (
                      <SelectItem key={m.id} value={m.id}>
                        {m.name} ({m.department})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </div>

          {/* Row 5: 비고 */}
          <div>
            <Label>비고</Label>
            <div className="mt-1">
              <Textarea
                value={formData.memo}
                onChange={(e) => handleChange('memo', e.target.value)}
                placeholder="비고를 입력하세요"
                rows={3}
              />
            </div>
          </div>

        </CardContent>
      </Card>

      {/* 하단 버튼 (sticky 하단 바) */}
      <div className={`fixed bottom-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[48px] ${sidebarCollapsed ? 'md:left-[156px]' : 'md:left-[316px]'} flex items-center justify-between`}>
        <Button
          variant="outline"
          onClick={() => router.push(listPath)}
          disabled={isSubmitting}
        >
          <X className="h-4 w-4 mr-1" />
          취소
        </Button>
        <Button onClick={handleSubmit} disabled={isSubmitting}>
          {isSubmitting ? <Loader2 className="h-4 w-4 mr-1 animate-spin" /> : <Save className="h-4 w-4 mr-1" />}
          저장
        </Button>
      </div>
    </div>
  );
}
