import { useState } from 'react';
import Swal from 'sweetalert2';

export interface UseJsonToTypeReturn {
  jsonInput: string;
  setJsonInput: (value: string) => void;
  typeOutput: string;
  setTypeOutput: (value: string) => void;
  typeName: string;
  setTypeName: (value: string) => void;
  error: string;
  setError: (value: string) => void;
  copied: boolean;
  setCopied: (value: boolean) => void;
  convertJsonToType: () => void;
  handleCopy: () => void;
  handleClear: () => void;
  loadExample: () => void;
}

const capitalize = (str: string): string => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

const getTypeFromValue = (value: unknown, key?: string): string => {
  if (value === null) return 'null';
  if (Array.isArray(value)) {
    if (value.length === 0) return 'any[]';
    const firstItem = value[0];
    const itemType = getTypeFromValue(firstItem);
    return `${itemType}[]`;
  }
  
  const type = typeof value;
  if (type === 'object') {
    return generateTypeDefinition(value, key ? capitalize(key) : 'NestedType', false);
  }
  
  return type;
};

const generateTypeDefinition = (obj: unknown, name: string, isRoot: boolean = true): string => {
  if (typeof obj !== 'object' || obj === null) {
    return typeof obj;
  }

  const entries = Object.entries(obj);
  const properties = entries.map(([key, value]) => {
    const typeStr = getTypeFromValue(value, key);
    return `  ${key}: ${typeStr};`;
  }).join('\n');

  return `${isRoot ? 'export ' : ''}interface ${name} {\n${properties}\n}`;
};

const exampleJson = `{
  "id": 1,
  "name": "John Doe",
  "email": "john@example.com",
  "age": 30,
  "isActive": true,
  "roles": ["admin", "user"],
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "zipCode": "10001"
  },
  "tags": ["developer", "designer"]
}`;

export const useJsonToType = (): UseJsonToTypeReturn => {
  const [jsonInput, setJsonInput] = useState('');
  const [typeOutput, setTypeOutput] = useState('');
  const [error, setError] = useState('');
  const [typeName, setTypeName] = useState('MyType');
  const [copied, setCopied] = useState(false);

  const convertJsonToType = () => {
    try {
      setError('');
      setCopied(false);
      
      if (!jsonInput.trim()) {
        Swal.fire({
          icon: 'warning',
          title: 'JSON Eksik',
          text: 'Lütfen bir JSON girin',
          confirmButtonText: 'Tamam',
        });
        setError('Lütfen bir JSON girin');
        return;
      }

      const parsed = JSON.parse(jsonInput);
      const result = generateTypeDefinition(parsed, typeName || 'MyType');
      setTypeOutput(result);
      
      // Başarılı dönüştürme mesajı
      Swal.fire({
        icon: 'success',
        title: 'Dönüştürme Başarılı!',
        text: 'TypeScript interface oluşturuldu',
        timer: 1500,
        showConfirmButton: false,
      });
    } catch (err) {
      const errorMsg = 'Geçersiz JSON formatı: ' + (err as Error).message;
      setError(errorMsg);
      setTypeOutput('');
      
      Swal.fire({
        icon: 'error',
        title: 'JSON Hatası',
        text: errorMsg,
        confirmButtonText: 'Tamam',
      });
    }
  };

  const handleCopy = () => {
    navigator.clipboard.writeText(typeOutput);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
    
    // Toast mesajı
    Swal.fire({
      toast: true,
      position: 'top-end',
      icon: 'success',
      title: 'Kopyalandı!',
      showConfirmButton: false,
      timer: 1500,
    });
  };

  const handleClear = () => {
    setJsonInput('');
    setTypeOutput('');
    setError('');
    setTypeName('MyType');
    setCopied(false);
  };

  const loadExample = () => {
    setJsonInput(exampleJson);
    setError('');
    setCopied(false);
  };

  return {
    jsonInput,
    setJsonInput,
    typeOutput,
    setTypeOutput,
    typeName,
    setTypeName,
    error,
    setError,
    copied,
    setCopied,
    convertJsonToType,
    handleCopy,
    handleClear,
    loadExample,
  };
};

