'use client';

import { useState, useEffect, useCallback } from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { DatePicker } from '@/components/ui/date-picker';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { Plus, Trash2 } from 'lucide-react';
import { getApprovalFormDetail } from './form-actions';
import type { ApprovalFormField } from './form-actions';

interface DynamicFormRendererProps {
  formId: number;
  data: Record<string, unknown>;
  onChange: (data: Record<string, unknown>) => void;
  onFieldsLoaded?: (fields: ApprovalFormField[]) => void;
}

/**
 * 동적 폼 렌더러
 * API template.fields 기반으로 폼 필드를 자동 생성
 */
export function DynamicFormRenderer({ formId, data, onChange, onFieldsLoaded }: DynamicFormRendererProps) {
  const [fields, setFields] = useState<ApprovalFormField[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const load = async () => {
      setIsLoading(true);
      setError(null);
      const result = await getApprovalFormDetail(formId);
      if (result.success && result.data) {
        const loadedFields = result.data.template.fields || [];
        setFields(loadedFields);
        onFieldsLoaded?.(loadedFields);
      } else {
        setError(result.error || '양식 정보를 불러올 수 없습니다.');
      }
      setIsLoading(false);
    };
    load();
  }, [formId]);

  const handleFieldChange = useCallback((name: string, value: unknown) => {
    onChange({ ...data, [name]: value });
  }, [data, onChange]);

  if (isLoading) {
    return (
      <div className="bg-white rounded-lg border p-6">
        <div className="animate-pulse space-y-4">
          <div className="h-6 bg-gray-200 rounded w-32" />
          <div className="h-10 bg-gray-200 rounded" />
          <div className="h-10 bg-gray-200 rounded" />
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-white rounded-lg border p-6">
        <p className="text-sm text-destructive">{error}</p>
      </div>
    );
  }

  if (fields.length === 0) {
    return (
      <div className="bg-white rounded-lg border p-6">
        <p className="text-sm text-muted-foreground">이 양식에는 입력 필드가 없습니다.</p>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-lg border p-6">
      <h3 className="text-lg font-semibold mb-4">문서 내용</h3>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {fields.map((field) => (
          <DynamicField
            key={field.name}
            field={field}
            value={data[field.name]}
            onChange={(value) => handleFieldChange(field.name, value)}
          />
        ))}
      </div>
    </div>
  );
}

// ===== 개별 필드 렌더러 =====

interface DynamicFieldProps {
  field: ApprovalFormField;
  value: unknown;
  onChange: (value: unknown) => void;
}

function DynamicField({ field, value, onChange }: DynamicFieldProps) {
  const isFullWidth = field.type === 'textarea' || field.type === 'array' || field.type === 'daterange';

  return (
    <div className={`space-y-2 ${isFullWidth ? 'md:col-span-2' : ''}`}>
      <Label>
        {field.label}
        {field.required && <span className="text-destructive ml-1">*</span>}
      </Label>
      {renderField(field, value, onChange)}
      {field.description && (
        <p className="text-xs text-muted-foreground">{field.description}</p>
      )}
    </div>
  );
}

function renderField(field: ApprovalFormField, value: unknown, onChange: (value: unknown) => void) {
  switch (field.type) {
    case 'text':
      return (
        <Input
          value={(value as string) || ''}
          onChange={(e) => onChange(e.target.value)}
          placeholder={field.placeholder || `${field.label} 입력`}
        />
      );

    case 'number':
      return (
        <Input
          type="number"
          value={(value as number) ?? ''}
          onChange={(e) => onChange(e.target.value ? Number(e.target.value) : '')}
          placeholder={field.placeholder || '0'}
        />
      );

    case 'textarea':
      return (
        <Textarea
          value={(value as string) || ''}
          onChange={(e) => onChange(e.target.value)}
          placeholder={field.placeholder || `${field.label} 입력`}
          rows={4}
        />
      );

    case 'date':
      return (
        <DatePicker
          value={(value as string) || ''}
          onChange={(date) => onChange(date)}
          placeholder={field.placeholder || '날짜 선택'}
        />
      );

    case 'daterange':
      return <DateRangeField value={value as { start?: string; end?: string }} onChange={onChange} field={field} />;

    case 'select':
      return (
        <Select
          key={`${field.name}-${(value as string) || 'empty'}`}
          value={(value as string) || undefined}
          onValueChange={onChange}
        >
          <SelectTrigger>
            <SelectValue placeholder={field.placeholder || '선택'} />
          </SelectTrigger>
          <SelectContent>
            {(field.options || []).map((option) => (
              <SelectItem key={option} value={option}>
                {option}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      );

    case 'checkbox':
      return (
        <div className="flex items-center space-x-2 pt-1">
          <Checkbox
            checked={(value as boolean) || false}
            onCheckedChange={(checked) => onChange(checked === true)}
          />
          <span className="text-sm">{field.placeholder || field.label}</span>
        </div>
      );

    case 'file':
      return (
        <Input
          type="file"
          onChange={(e) => {
            const files = e.target.files;
            if (files) onChange(Array.from(files));
          }}
          multiple
        />
      );

    case 'array':
      return <ArrayField field={field} value={value as Record<string, unknown>[]} onChange={onChange} />;

    default:
      return (
        <Input
          value={(value as string) || ''}
          onChange={(e) => onChange(e.target.value)}
          placeholder={field.placeholder || `${field.label} 입력`}
        />
      );
  }
}

// ===== 날짜 범위 필드 =====
function DateRangeField({
  value,
  onChange,
  field,
}: {
  value?: { start?: string; end?: string };
  onChange: (value: unknown) => void;
  field: ApprovalFormField;
}) {
  const rangeValue = value || { start: '', end: '' };

  return (
    <div className="flex items-center gap-2">
      <div className="flex-1 min-w-0">
        <DatePicker
          value={rangeValue.start || ''}
          onChange={(date) => onChange({ ...rangeValue, start: date })}
          placeholder="시작일"
        />
      </div>
      <span className="text-muted-foreground shrink-0">~</span>
      <div className="flex-1 min-w-0">
        <DatePicker
          value={rangeValue.end || ''}
          onChange={(date) => onChange({ ...rangeValue, end: date })}
          placeholder="종료일"
        />
      </div>
    </div>
  );
}

// ===== 배열(테이블) 필드 =====
function ArrayField({
  field,
  value,
  onChange,
}: {
  field: ApprovalFormField;
  value?: Record<string, unknown>[];
  onChange: (value: unknown) => void;
}) {
  const rows = value || [];
  const columns = field.columns || [];

  const addRow = () => {
    const newRow: Record<string, unknown> = {};
    columns.forEach((col) => {
      newRow[col.name] = col.type === 'number' ? 0 : '';
    });
    onChange([...rows, newRow]);
  };

  const removeRow = (index: number) => {
    onChange(rows.filter((_, i) => i !== index));
  };

  const updateRow = (index: number, colName: string, colValue: unknown) => {
    const updated = [...rows];
    updated[index] = { ...updated[index], [colName]: colValue };
    onChange(updated);
  };

  if (columns.length === 0) {
    return <p className="text-sm text-muted-foreground">배열 필드 컬럼이 정의되지 않았습니다.</p>;
  }

  return (
    <div className="space-y-2">
      <div className="overflow-x-auto">
        <table className="w-full border text-sm">
          <thead>
            <tr className="bg-gray-50">
              <th className="border px-2 py-1 w-10">No</th>
              {columns.map((col) => (
                <th key={col.name} className="border px-2 py-1">{col.label}</th>
              ))}
              <th className="border px-2 py-1 w-10" />
            </tr>
          </thead>
          <tbody>
            {rows.map((row, rowIdx) => (
              <tr key={rowIdx}>
                <td className="border px-2 py-1 text-center">{rowIdx + 1}</td>
                {columns.map((col) => (
                  <td key={col.name} className="border px-1 py-1">
                    {col.type === 'number' ? (
                      <Input
                        type="number"
                        className="h-8 text-sm"
                        value={(row[col.name] as number) ?? ''}
                        onChange={(e) => updateRow(rowIdx, col.name, e.target.value ? Number(e.target.value) : '')}
                      />
                    ) : col.type === 'date' ? (
                      <DatePicker
                        size="sm"
                        value={(row[col.name] as string) || ''}
                        onChange={(date) => updateRow(rowIdx, col.name, date)}
                      />
                    ) : col.type === 'select' ? (
                      <Select
                        key={`${col.name}-${rowIdx}-${(row[col.name] as string) || 'empty'}`}
                        value={(row[col.name] as string) || undefined}
                        onValueChange={(v) => updateRow(rowIdx, col.name, v)}
                      >
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue placeholder="선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {(col.options || []).map((opt) => (
                            <SelectItem key={opt} value={opt}>{opt}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    ) : (
                      <Input
                        className="h-8 text-sm"
                        value={(row[col.name] as string) || ''}
                        onChange={(e) => updateRow(rowIdx, col.name, e.target.value)}
                      />
                    )}
                  </td>
                ))}
                <td className="border px-1 py-1 text-center">
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-6 w-6"
                    onClick={() => removeRow(rowIdx)}
                  >
                    <Trash2 className="h-3 w-3 text-destructive" />
                  </Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <Button variant="outline" size="sm" onClick={addRow}>
        <Plus className="h-3 w-3 mr-1" />
        행 추가
      </Button>
    </div>
  );
}
