'use client';

import React from 'react';
import { useSession } from 'next-auth/react';
//import 'bootstrap/dist/css/bootstrap.min.css';
import { useJsonToType } from './hooks/useJsonToType';
import { useJsonToTypeApi } from './hooks/useJsonToTypeApi';
import { useJsonToTypeList } from './hooks/useJsonToTypeList';
import PreloaderAndSearch from "@/components/PreloaderAndSearch";
import Header from "@/components/Header";

export default function JsonToTypePage() {
  const { status } = useSession();
  
  // Converter logic
  const {
    jsonInput,
    setJsonInput,
    typeOutput,
    setTypeOutput,
    typeName,
    setTypeName,
    error,
    copied,
    convertJsonToType,
    handleCopy,
    handleClear: clearConverter,
    loadExample,
  } = useJsonToType();

  // API logic
  const {
    title,
    setTitle,
    saveSuccess,
    saveError,
    isSaving,
    handleSave: saveToApi,
    clearMessages,
  } = useJsonToTypeApi();

  // List logic
  const {
    items,
    isLoading,
    fetchItems,
    loadItem,
    downloadJson,
    downloadType,
    deleteItem,
  } = useJsonToTypeList((jsonData, typeData, itemTitle) => {
    setJsonInput(jsonData);
    setTypeOutput(typeData);
    setTitle(itemTitle);
  });

  const handleClear = () => {
    clearConverter();
    setTitle('');
    clearMessages();
  };

  const handleSave = async () => {
    await saveToApi(jsonInput, typeOutput);
    // Kayıt başarılıysa listeyi yenile
    fetchItems();
  };

  return (
    <>
      <PreloaderAndSearch />
      
      <Header />

      {/* Spacer for fixed header */}
      <div style={{ height: '150px' }}></div>

      <div className="min-vh-100 bg-light py-5">
        <div className="container">
          <div className="row mb-4">
            <div className="col-12">
              <div className="text-center">
                <h1 className="display-4 fw-bold text-primary mb-3">
                  <i className="bi bi-code-square me-3"></i>
                  JSON to TypeScript Converter
                </h1>
                <p className="lead text-muted">
                  JSON verilerinizi TypeScript interface tanımlarına kolayca dönüştürün
                </p>
              </div>
            </div>
          </div>

          <div className="row g-4">
            {/* Input Section */}
            <div className="col-lg-6">
              <div className="card shadow-sm border-0 h-100">
                <div className="card-header bg-primary text-white py-3">
                  <h5 className="mb-0">
                    <i className="bi bi-file-earmark-code me-2"></i>
                    JSON Input
                  </h5>
                </div>
                <div className="card-body">
                  <div className="mb-3">
                    <label htmlFor="title" className="form-label fw-semibold">
                      <i className="bi bi-bookmark me-1"></i>
                      Başlık:
                    </label>
                    <input
                      type="text"
                      className="form-control"
                      id="title"
                      value={title}
                      onChange={(e) => setTitle(e.target.value)}
                      placeholder="Örn: User API Response Type"
                    />
                    <small className="text-muted">Kaydetmek için bir başlık girin</small>
                  </div>

                  <div className="mb-3">
                    <label htmlFor="typeName" className="form-label fw-semibold">
                      Interface Adı:
                    </label>
                    <input
                      type="text"
                      className="form-control"
                      id="typeName"
                      value={typeName}
                      onChange={(e) => setTypeName(e.target.value)}
                      placeholder="MyType"
                    />
                  </div>
                  
                  <div className="mb-3">
                    <label htmlFor="jsonInput" className="form-label fw-semibold">
                      JSON Veriniz:
                    </label>
                    <textarea
                      className="form-control font-monospace"
                      id="jsonInput"
                      rows={15}
                      value={jsonInput}
                      onChange={(e) => setJsonInput(e.target.value)}
                      placeholder="JSON kodunuzu buraya yapıştırın..."
                      style={{ fontSize: '0.9rem' }}
                    />
                  </div>

                  {error && (
                    <div className="alert alert-danger d-flex align-items-center" role="alert">
                      <i className="bi bi-exclamation-triangle-fill me-2"></i>
                      <div>{error}</div>
                    </div>
                  )}

                  <div className="d-flex gap-2 flex-wrap">
                    <button
                      className="btn btn-primary btn-lg"
                      onClick={convertJsonToType}
                    >
                      <i className="bi bi-arrow-right-circle me-2"></i>
                      Dönüştür
                    </button>
                    <button
                      className="btn btn-outline-secondary"
                      onClick={loadExample}
                    >
                      <i className="bi bi-file-earmark-text me-2"></i>
                      Örnek Yükle
                    </button>
                    <button
                      className="btn btn-outline-danger"
                      onClick={handleClear}
                    >
                      <i className="bi bi-trash me-2"></i>
                      Temizle
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {/* Output Section */}
            <div className="col-lg-6">
              <div className="card shadow-sm border-0 h-100">
                <div className="card-header bg-success text-white py-3">
                  <h5 className="mb-0">
                    <i className="bi bi-file-earmark-code-fill me-2"></i>
                    TypeScript Output
                  </h5>
                </div>
                <div className="card-body">
                  {typeOutput ? (
                    <>
                      <div className="mb-3">
                        <div className="d-flex justify-content-between align-items-center mb-2">
                          <label className="form-label fw-semibold mb-0">
                            TypeScript Interface:
                          </label>
                          <button
                            className={`btn btn-sm ${copied ? 'btn-success' : 'btn-outline-primary'}`}
                            onClick={handleCopy}
                          >
                            <i className={`bi ${copied ? 'bi-check-circle-fill' : 'bi-clipboard'} me-1`}></i>
                            {copied ? 'Kopyalandı!' : 'Kopyala'}
                          </button>
                        </div>
                        <pre className="bg-dark text-light p-3 rounded" style={{ maxHeight: '400px', overflow: 'auto' }}>
                          <code>{typeOutput}</code>
                        </pre>
                      </div>

                      {/* Save Success/Error Messages */}
                      {saveSuccess && (
                        <div className="alert alert-success d-flex align-items-center mb-3" role="alert">
                          <i className="bi bi-check-circle-fill me-2"></i>
                          <div>{saveSuccess}</div>
                        </div>
                      )}

                      {saveError && (
                        <div className="alert alert-danger d-flex align-items-center mb-3" role="alert">
                          <i className="bi bi-exclamation-triangle-fill me-2"></i>
                          <div>{saveError}</div>
                        </div>
                      )}

                      {/* Save Button */}
                      <div className="d-grid gap-2">
                        <button
                          className="btn btn-success btn-lg"
                          onClick={handleSave}
                          disabled={isSaving || !title.trim()}
                        >
                          {isSaving ? (
                            <>
                              <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                              Kaydediliyor...
                            </>
                          ) : (
                            <>
                              <i className="bi bi-save me-2"></i>
                              Kaydet
                            </>
                          )}
                        </button>
                        {status !== 'authenticated' && (
                          <small className="text-danger text-center">
                            <i className="bi bi-lock me-1"></i>
                            Kaydetmek için giriş yapmalısınız
                          </small>
                        )}
                        {!title.trim() && typeOutput && (
                          <small className="text-warning text-center">
                            <i className="bi bi-exclamation-circle me-1"></i>
                            Kaydetmek için başlık girmelisiniz
                          </small>
                        )}
                      </div>
                    </>
                  ) : (
                    <div className="text-center text-muted py-5">
                      <i className="bi bi-arrow-left-circle display-1 mb-3"></i>
                      <p className="lead">
                        Dönüştürülmüş TypeScript kodunuz burada görünecek
                      </p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* Features Section */}
          <div className="row mt-5">
            <div className="col-12">
              <div className="card shadow-sm border-0">
                <div className="card-body">
                  <h5 className="card-title mb-3">
                    <i className="bi bi-info-circle me-2"></i>
                    Özellikler
                  </h5>
                  <div className="row">
                    <div className="col-md-4 mb-3">
                      <div className="d-flex">
                        <i className="bi bi-check-circle-fill text-success me-2"></i>
                        <div>
                          <strong>Otomatik Tip Algılama</strong>
                          <p className="text-muted small mb-0">String, number, boolean, array ve nested object desteklenir</p>
                        </div>
                      </div>
                    </div>
                    <div className="col-md-4 mb-3">
                      <div className="d-flex">
                        <i className="bi bi-check-circle-fill text-success me-2"></i>
                        <div>
                          <strong>İç İçe Objeler</strong>
                          <p className="text-muted small mb-0">Karmaşık JSON yapılarını otomatik olarak interface'lere dönüştürür</p>
                        </div>
                      </div>
                    </div>
                    <div className="col-md-4 mb-3">
                      <div className="d-flex">
                        <i className="bi bi-check-circle-fill text-success me-2"></i>
                        <div>
                          <strong>Hızlı Kopyalama</strong>
                          <p className="text-muted small mb-0">Tek tıkla oluşturulan kodu kopyalayın</p>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Saved Items Section */}
          {status === 'authenticated' && (
            <div className="row mt-5">
              <div className="col-12">
                <div className="card shadow-sm border-0">
                  <div className="card-header bg-info text-white py-3">
                    <div className="d-flex justify-content-between align-items-center">
                      <h5 className="mb-0">
                        <i className="bi bi-folder me-2"></i>
                        Kayıtlı Dönüşümlerim ({items.length})
                      </h5>
                      <button
                        className="btn btn-light btn-sm"
                        onClick={fetchItems}
                        disabled={isLoading}
                      >
                        <i className="bi bi-arrow-clockwise me-1"></i>
                        Yenile
                      </button>
                    </div>
                  </div>
                  <div className="card-body">
                    {isLoading ? (
                      <div className="text-center py-5">
                        <div className="spinner-border text-primary" role="status">
                          <span className="visually-hidden">Yükleniyor...</span>
                        </div>
                      </div>
                    ) : items.length === 0 ? (
                      <div className="text-center text-muted py-5">
                        <i className="bi bi-inbox display-1 mb-3"></i>
                        <p className="lead">Henüz kaydedilmiş dönüşüm yok</p>
                        <p className="small">Dönüşümlerinizi kaydedin ve buradan kolayca erişin</p>
                      </div>
                    ) : (
                      <div className="table-responsive">
                        <table className="table table-hover">
                          <thead>
                            <tr>
                              <th>Başlık</th>
                              <th>Tarih</th>
                              <th className="text-end">İşlemler</th>
                            </tr>
                          </thead>
                          <tbody>
                            {items.map((item) => (
                              <tr key={item.id}>
                                <td>
                                  <strong>{item.title}</strong>
                                </td>
                                <td>
                                  <small className="text-muted">
                                    {new Date(item.created_at).toLocaleDateString('tr-TR', {
                                      year: 'numeric',
                                      month: 'short',
                                      day: 'numeric',
                                      hour: '2-digit',
                                      minute: '2-digit',
                                    })}
                                  </small>
                                </td>
                                <td>
                                  <div className="d-flex gap-2 justify-content-end">
                                    <button
                                      className="btn btn-sm btn-primary"
                                      onClick={() => loadItem(item)}
                                      title="Yükle"
                                    >
                                      <i className="bi bi-upload me-1"></i>
                                      Yükle
                                    </button>
                                    <button
                                      className="btn btn-sm btn-success"
                                      onClick={() => downloadJson(item)}
                                      title="JSON İndir"
                                    >
                                      <i className="bi bi-filetype-json me-1"></i>
                                      JSON
                                    </button>
                                    <button
                                      className="btn btn-sm btn-info text-white"
                                      onClick={() => downloadType(item)}
                                      title="TypeScript İndir"
                                    >
                                      <i className="bi bi-filetype-tsx me-1"></i>
                                      TS
                                    </button>
                                    <button
                                      className="btn btn-sm btn-danger"
                                      onClick={() => deleteItem(item.id)}
                                      title="Sil"
                                    >
                                      <i className="bi bi-trash me-1"></i>
                                      Sil
                                    </button>
                                  </div>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}