import React, { useState } from 'react';
import { SiteSettings, CustomPage } from '../types';
import { FileText, Plus, X, Save, Edit, Trash2, ShieldCheck, RotateCcw, ArrowLeftRight, XCircle } from 'lucide-react';

interface CustomPagesEditorProps {
  settings: SiteSettings;
  updateSettings: (updates: Partial<SiteSettings>) => Promise<void>;
}

// Slug generation function that supports Bengali characters
const createSlug = (text: string): string => {
  if (!text) return '';
  return text
    .normalize('NFC')
    .toLowerCase()
    .trim()
    .replace(/[^\u0980-\u09FFa-z0-9\s-]/g, '') // Allow Bengali, alphanumeric, space, hyphen
    .replace(/\s+/g, '-'); // Replace spaces with hyphens
}

// Default policy content
const DEFAULT_POLICIES = [
  {
    id: 'return-policy',
    label: 'Return Policy',
    icon: 'RotateCcw',
    color: '#F37021',
    gradient: 'from-orange-500 to-orange-600',
    defaultContent: `We want you to be 100% satisfied with your purchase.

Returns must be initiated within 48 hours of receiving your order. Products must be unused, unopened, and in original packaging.

To request a return, contact us via WhatsApp or phone with your Order ID and a photo of the product.

Perishable goods, opened food items, or products damaged by misuse are not eligible for return.

Return shipping cost is the customer's responsibility unless the product was defective or a wrong item was delivered.

Once we receive and inspect the returned product, we will process your exchange or refund within 3-5 business days.`,
  },
  {
    id: 'exchange-policy',
    label: 'Exchange Policy',
    icon: 'ArrowLeftRight',
    color: '#10B981',
    gradient: 'from-emerald-500 to-emerald-600',
    defaultContent: `Easy product exchanges to ensure your satisfaction.

Exchanges must be requested within 48 hours of delivery. Products must be in their original, unopened condition.

Only products with manufacturing defects, wrong items, or damaged packaging qualify for direct exchange without additional charges.

Reach out to our support team with your Order ID and clear images of the issue. We will arrange a pickup and send a replacement.

For defective or wrong products, we cover the exchange shipping. For preference-based exchanges, shipping cost is borne by the customer.`,
  },
  {
    id: 'cancellation-policy',
    label: 'Cancellation Policy',
    icon: 'XCircle',
    color: '#8B5CF6',
    gradient: 'from-violet-500 to-violet-600',
    defaultContent: `Flexible cancellation options for your convenience.

You can cancel your order free of charge anytime before it has been dispatched from our warehouse.

Once the order has been dispatched, it cannot be cancelled. You may request a return after receiving the product.

To cancel, send your Order ID via WhatsApp or call our support. Cancellations are accepted during business hours (9AM – 6PM).

For prepaid orders, the full amount will be refunded within 3-5 business days to your original payment method.

We do not charge any cancellation fees for orders cancelled before dispatch.`,
  },
  {
    id: 'refund-only-policy',
    label: 'Refund Policy',
    icon: 'ShieldCheck',
    color: '#3B82F6',
    gradient: 'from-blue-500 to-blue-600',
    defaultContent: `Transparent and hassle-free refund process.

Refunds are issued for defective products, wrong items delivered, or orders cancelled before dispatch. Opened or used products are not eligible.

Once your refund request is approved, we process it within 3-5 business days. You will receive a confirmation notification.

Refunds are issued via bKash, Nagad, or bank transfer — whichever you prefer. Please provide your account details when requesting.

In some cases (partially damaged order, missing items), only a partial refund may be issued equivalent to the value of the affected items.`,
  },
];

const CustomPagesEditor: React.FC<CustomPagesEditorProps> = ({ settings, updateSettings }) => {
  const [pages, setPages] = useState<CustomPage[]>(() => {
    try {
      if (settings.customPagesJson) return JSON.parse(settings.customPagesJson);
    } catch { }
    return [];
  });

  const [policyPages, setPolicyPages] = useState<Record<string, string>>(() => {
    try {
      if (settings.policyPagesJson) return JSON.parse(settings.policyPagesJson);
    } catch { }
    return {};
  });

  const [editingPage, setEditingPage] = useState<CustomPage | null>(null);
  const [editingPolicy, setEditingPolicy] = useState<string | null>(null); // id of policy being edited
  const [policyDraft, setPolicyDraft] = useState<string>('');
  const [activeTab, setActiveTab] = useState<'custom' | 'policy'>('policy');
  const [filterTheme, setFilterTheme] = useState<string>(settings.landingTheme || '01');

  const THEMES = ['01', '02', '03', '04', '05'] as const;

  const displayedPages = filterTheme === 'all'
    ? pages
    : pages.filter(p => p.assignedThemes.includes(filterTheme as any));

  const handleSaveCustomPage = () => {
    if (!editingPage) return;
    let finalPage = { ...editingPage };
    if (!finalPage.slug || finalPage.slug.startsWith('new-page-')) {
      finalPage.slug = createSlug(finalPage.title);
    }
    const existingIndex = pages.findIndex(p => p.id === editingPage.id);
    let newPages = [...pages];
    if (existingIndex >= 0) {
      newPages[existingIndex] = finalPage;
    } else {
      newPages.push(finalPage);
    }
    setPages(newPages);
    updateSettings({ customPagesJson: JSON.stringify(newPages) });
    setEditingPage(null);
  };

  const handleDelete = (id: string) => {
    if (window.confirm('Are you sure you want to delete this page?')) {
      const newPages = pages.filter(p => p.id !== id);
      setPages(newPages);
      updateSettings({ customPagesJson: JSON.stringify(newPages) });
    }
  };

  const handleEditPolicy = (id: string) => {
    const policy = DEFAULT_POLICIES.find(p => p.id === id)!;
    setPolicyDraft(policyPages[id] ?? policy.defaultContent);
    setEditingPolicy(id);
  };

  const handleSavePolicy = () => {
    if (!editingPolicy) return;
    const updated = { ...policyPages, [editingPolicy]: policyDraft };
    setPolicyPages(updated);
    updateSettings({ policyPagesJson: JSON.stringify(updated) });
    setEditingPolicy(null);
  };

  const handleResetPolicy = (id: string) => {
    const policy = DEFAULT_POLICIES.find(p => p.id === id)!;
    const updated = { ...policyPages, [id]: policy.defaultContent };
    setPolicyPages(updated);
    updateSettings({ policyPagesJson: JSON.stringify(updated) });
  };

  return (
    <div className="space-y-8 animate-fade-in-up">
      {/* Tab Switch */}
      <div className="flex gap-2 p-1 bg-slate-100 rounded-2xl w-fit">
        <button
          onClick={() => setActiveTab('policy')}
          className={`px-6 py-2.5 rounded-xl font-bold text-sm transition-all ${activeTab === 'policy' ? 'bg-white shadow-sm text-slate-800' : 'text-slate-500 hover:text-slate-700'}`}
        >
          🔒 Policy Pages
        </button>
        <button
          onClick={() => setActiveTab('custom')}
          className={`px-6 py-2.5 rounded-xl font-bold text-sm transition-all ${activeTab === 'custom' ? 'bg-white shadow-sm text-slate-800' : 'text-slate-500 hover:text-slate-700'}`}
        >
          📄 Custom Pages
        </button>
      </div>

      {/* ==== POLICY PAGES TAB ==== */}
      {activeTab === 'policy' && (
        <div className="bg-white dark:bg-slate-900 border p-8 rounded-[40px] shadow-sm">
          <div className="mb-8">
            <h2 className="text-3xl font-black mb-2 flex items-center gap-3">
              <ShieldCheck className="text-[#F37021]" size={32} /> Policy Pages
            </h2>
            <p className="text-slate-500">Edit the content of Return, Exchange, Cancellation, and Refund policy pages shown to customers.</p>
          </div>

          {editingPolicy ? (
            // Editor view
            (() => {
              const policy = DEFAULT_POLICIES.find(p => p.id === editingPolicy)!;
              return (
                <div className="bg-slate-50 rounded-3xl border p-6 space-y-4">
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-xl flex items-center justify-center text-white" style={{ background: policy.color }}>
                        {policy.icon === 'RotateCcw' && <RotateCcw size={18} />}
                        {policy.icon === 'ArrowLeftRight' && <ArrowLeftRight size={18} />}
                        {policy.icon === 'XCircle' && <XCircle size={18} />}
                        {policy.icon === 'ShieldCheck' && <ShieldCheck size={18} />}
                      </div>
                      <h3 className="text-xl font-black text-slate-800">{policy.label}</h3>
                    </div>
                    <button onClick={() => setEditingPolicy(null)} className="p-2 hover:bg-slate-200 rounded-full transition">
                      <X size={20} />
                    </button>
                  </div>
                  <p className="text-xs text-slate-400 mb-2">Write each point as a separate paragraph. Use plain text — no HTML needed.</p>
                  <textarea
                    value={policyDraft}
                    onChange={(e) => setPolicyDraft(e.target.value)}
                    rows={16}
                    className="w-full border border-slate-200 px-4 py-3 rounded-2xl text-sm leading-relaxed resize-y focus:outline-none focus:border-slate-400 text-black font-bold placeholder-slate-400"
                    placeholder="Write policy content here..."
                  />
                  <div className="flex justify-between items-center pt-2">
                    <button
                      onClick={() => setPolicyDraft(DEFAULT_POLICIES.find(p => p.id === editingPolicy)!.defaultContent)}
                      className="text-xs text-slate-400 hover:text-slate-600 font-bold flex items-center gap-1"
                    >
                      <RotateCcw size={12} /> Reset to default
                    </button>
                    <button
                      onClick={handleSavePolicy}
                      className="flex items-center gap-2 text-white font-bold px-6 py-3 rounded-xl transition"
                      style={{ background: policy.color }}
                    >
                      <Save size={18} /> Save Policy
                    </button>
                  </div>
                </div>
              );
            })()
          ) : (
            // List of policy cards
            <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
              {DEFAULT_POLICIES.map((policy) => {
                const hasCustomContent = !!policyPages[policy.id];
                return (
                  <div key={policy.id} className="bg-slate-50 border border-slate-100 rounded-2xl p-5 flex flex-col gap-4">
                    <div className="flex items-start gap-4">
                      <div className="w-12 h-12 rounded-xl flex items-center justify-center text-white shrink-0" style={{ background: policy.color }}>
                        {policy.icon === 'RotateCcw' && <RotateCcw size={22} />}
                        {policy.icon === 'ArrowLeftRight' && <ArrowLeftRight size={22} />}
                        {policy.icon === 'XCircle' && <XCircle size={22} />}
                        {policy.icon === 'ShieldCheck' && <ShieldCheck size={22} />}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <h3 className="font-black text-slate-800">{policy.label}</h3>
                          {hasCustomContent ? (
                            <span className="text-[10px] font-bold bg-green-100 text-green-700 px-2 py-0.5 rounded-full">Custom</span>
                          ) : (
                            <span className="text-[10px] font-bold bg-slate-200 text-slate-500 px-2 py-0.5 rounded-full">Default</span>
                          )}
                        </div>
                        <p className="text-xs text-slate-400 line-clamp-2 leading-relaxed">
                          {(policyPages[policy.id] ?? policy.defaultContent).split('\n')[0]}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2 pt-1">
                      <button
                        onClick={() => handleEditPolicy(policy.id)}
                        className="flex-1 flex items-center justify-center gap-1 border border-slate-200 hover:border-slate-400 bg-white text-slate-700 font-bold py-2 rounded-xl text-xs transition"
                      >
                        <Edit size={13} /> Edit Content
                      </button>
                      {hasCustomContent && (
                        <button
                          onClick={() => handleResetPolicy(policy.id)}
                          className="flex items-center gap-1 border border-red-100 hover:border-red-300 bg-red-50 text-red-500 font-bold py-2 px-3 rounded-xl text-xs transition"
                          title="Reset to default"
                        >
                          <RotateCcw size={13} />
                        </button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* ==== CUSTOM PAGES TAB ==== */}
      {activeTab === 'custom' && (
        <div className="bg-white dark:bg-slate-900 border p-8 rounded-[40px] shadow-sm relative overflow-hidden">
          <div className="absolute -top-32 -right-32 w-96 h-96 bg-blue-50 dark:bg-blue-950/20 rounded-full blur-3xl -z-10"></div>
          <div className="flex justify-between items-center mb-8">
            <div>
              <h2 className="text-3xl font-black mb-2 flex items-center gap-3"><FileText className="text-blue-600" size={32} /> Custom Pages</h2>
              <p className="text-slate-500">Create and manage content pages like About Us, Privacy Policy, or custom campaigns.</p>
            </div>
            <button
              onClick={() => setEditingPage({ id: `page-${Date.now()}`, title: 'New Page', slug: `new-page-${Date.now()}`, content: '', status: 'draft', assignedThemes: [] })}
              className="bg-blue-600 hover:bg-blue-700 text-white font-black px-6 py-3 rounded-2xl shadow-xl shadow-blue-600/20 flex items-center gap-2 transition-all"
            >
              <Plus size={20} /> Create Page
            </button>
          </div>

          {editingPage ? (
            <div className="bg-slate-50 p-8 rounded-[32px] border">
              <div className="flex justify-between items-center mb-6">
                <h3 className="text-2xl font-black text-slate-800">{editingPage.id.startsWith('page-') ? 'Create Page' : 'Edit Page'}</h3>
                <button onClick={() => setEditingPage(null)} className="p-2 hover:bg-slate-200 rounded-full transition-colors"><X size={24} /></button>
              </div>
              <div className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-black text-black mb-2">Page Title</label>
                    <input type="text" value={editingPage.title} onChange={(e) => setEditingPage({ ...editingPage, title: e.target.value })} className="w-full border-slate-200 px-4 py-3 rounded-xl text-black font-bold placeholder-slate-400 outline-none focus:border-blue-500" placeholder="e.g. Terms of Service" />
                  </div>
                  <div>
                    <label className="block text-sm font-black text-black mb-2">URL Slug</label>
                    <input type="text" value={editingPage.slug} onChange={(e) => setEditingPage({ ...editingPage, slug: e.target.value })} className="w-full border-slate-200 px-4 py-3 rounded-xl text-black font-bold placeholder-slate-400 outline-none focus:border-blue-500" placeholder="e.g. terms-of-service" />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-black text-black mb-2">Page Content (HTML/Text)</label>
                  <textarea rows={12} value={editingPage.content} onChange={(e) => setEditingPage({ ...editingPage, content: e.target.value })} className="w-full border-slate-200 px-4 py-3 rounded-xl font-mono text-sm text-black font-bold placeholder-slate-400 outline-none focus:border-blue-500" placeholder="<h1>Title</h1><br/><p>Content follows...</p>" />
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-bold text-slate-700 mb-2">Status</label>
                    <select value={editingPage.status} onChange={(e) => setEditingPage({ ...editingPage, status: e.target.value as any })} className="w-full border-slate-200 px-4 py-3 rounded-xl">
                      <option value="draft">Draft (Hidden)</option>
                      <option value="published">Published</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-bold text-slate-700 mb-2">Show in Navigation For Themes:</label>
                    <div className="flex flex-wrap gap-3">
                      {THEMES.map(t => (
                        <label key={t} className="flex items-center gap-2 bg-white px-3 py-2 rounded-lg border cursor-pointer hover:bg-slate-50">
                          <input type="checkbox" checked={editingPage.assignedThemes.includes(t)} onChange={(e) => {
                            const newThemes = e.target.checked
                              ? [...editingPage.assignedThemes, t]
                              : editingPage.assignedThemes.filter(th => th !== t);
                            setEditingPage({ ...editingPage, assignedThemes: newThemes });
                          }} className="rounded text-blue-600 focus:ring-blue-500 w-4 h-4" />
                          <span className="text-sm font-bold">Theme {t}</span>
                        </label>
                      ))}
                    </div>
                  </div>
                </div>
                <div className="flex justify-end pt-6 border-t border-slate-200">
                  <button onClick={handleSaveCustomPage} className="flex items-center gap-2 bg-slate-900 text-white font-bold px-8 py-4 rounded-xl hover:bg-slate-800 transition">
                    <Save size={20} /> Save Page
                  </button>
                </div>
              </div>
            </div>
          ) : (
            <div className="space-y-6">
              <div className="flex justify-between items-center bg-slate-50 p-4 rounded-2xl border">
                <span className="font-bold text-slate-700">Filter Pages by Theme:</span>
                <select value={filterTheme} onChange={(e) => setFilterTheme(e.target.value)} className="border-slate-200 px-4 py-2 rounded-xl font-bold bg-white">
                  <option value="all">Show All Pages</option>
                  <option value="01">Theme 01</option>
                  <option value="02">Theme 02</option>
                  <option value="03">Theme 03</option>
                  <option value="04">Theme 04</option>
                  <option value="05">Theme 05</option>
                </select>
              </div>
              {displayedPages.length === 0 ? (
                <div className="text-center py-16 bg-slate-50 rounded-[32px] border-2 border-dashed border-slate-200">
                  <FileText size={48} className="mx-auto text-slate-300 mb-4" />
                  <h3 className="text-xl font-black text-slate-800 mb-2">No pages found</h3>
                  <p className="text-slate-500">No pages are assigned to this theme yet.</p>
                </div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-left border-collapse">
                    <thead>
                      <tr className="border-b-2 border-slate-100">
                        <th className="py-4 px-4 font-black uppercase text-xs text-slate-500 tracking-wider">Title</th>
                        <th className="py-4 px-4 font-black uppercase text-xs text-slate-500 tracking-wider">Slug</th>
                        <th className="py-4 px-4 font-black uppercase text-xs text-slate-500 tracking-wider">Status</th>
                        <th className="py-4 px-4 font-black uppercase text-xs text-slate-500 tracking-wider">Visible In Themes</th>
                        <th className="py-4 px-4 font-black uppercase text-xs text-slate-500 tracking-wider text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {displayedPages.map(page => (
                        <tr key={page.id} className="border-b border-slate-50 hover:bg-slate-50 transition-colors">
                          <td className="py-4 px-4 font-bold text-slate-800">{page.title}</td>
                          <td className="py-4 px-4 text-slate-500 text-sm">/{page.slug}</td>
                          <td className="py-4 px-4">
                            <span className={`px-3 py-1 text-xs font-bold rounded-full ${page.status === 'published' ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-700'}`}>{page.status}</span>
                          </td>
                          <td className="py-4 px-4">
                            <div className="flex gap-1">
                              {page.assignedThemes.length > 0
                                ? page.assignedThemes.map(t => <span key={t} className="bg-blue-50 text-blue-600 text-[10px] font-black px-2 py-0.5 rounded">T{t}</span>)
                                : <span className="text-slate-400 text-xs italic">Hidden</span>
                              }
                            </div>
                          </td>
                          <td className="py-4 px-4 flex justify-end gap-2">
                            <button onClick={() => setEditingPage(page)} className="p-2 hover:bg-slate-200 rounded-lg text-slate-600 transition"><Edit size={16} /></button>
                            <button onClick={() => handleDelete(page.id)} className="p-2 hover:bg-red-100 rounded-lg text-red-500 transition"><Trash2 size={16} /></button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default CustomPagesEditor;
