'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { Download, BookOpen, ExternalLink, ShieldCheck, FileArchive, Key, ShoppingCart, AlertCircle } from 'lucide-react';
import { useAuth } from '@/context/AuthContext';
import { License } from '@/types';
import UserSidebar from '@/components/user/UserSidebar';

export default function UserDownloadsPage() {
  const { user } = useAuth();
  const [licenses, setLicenses] = useState<License[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadLicenses() {
      try {
        const res = await fetch('/api/licenses');
        const data = await res.json();
        if (data.licenses) {
          const userLics = data.licenses.filter(
            (l: License) => !user || l.user_id === user.id || l.user_id === 'usr-teamrafi' || l.user_id === 'usr-demo'
          );
          setLicenses(userLics);
        }
      } catch (e) {
        console.error('Failed to load user licenses:', e);
      } finally {
        setLoading(false);
      }
    }
    loadLicenses();
  }, [user]);

  const activeLicenses = licenses.filter((l) => l.status === 'active' || l.status === 'trial');

  return (
    <div className="py-8 md:py-12 bg-gray-50 min-h-screen">
      <div className="container mx-auto px-4 max-w-7xl">
        <div className="flex flex-col lg:flex-row gap-8 items-start">
          <UserSidebar />

          <div className="flex-1 space-y-6 w-full">
            <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-gray-100">
              <h1 className="text-2xl sm:text-3xl font-black text-gray-900">
                Licensed Downloads Portal
              </h1>
              <p className="text-xs sm:text-sm text-gray-500 mt-1">
                Download verified source code packages, WHMCS modules, and documentation for your active licenses.
              </p>
            </div>

            {loading ? (
              <div className="p-12 text-center text-gray-400 font-medium bg-white rounded-3xl border border-gray-100">
                Loading licensed files...
              </div>
            ) : activeLicenses.length === 0 ? (
              <div className="bg-white rounded-3xl p-10 text-center border border-dashed border-gray-200 space-y-4">
                <div className="w-16 h-16 bg-amber-50 text-amber-600 rounded-full flex items-center justify-center mx-auto">
                  <AlertCircle className="w-8 h-8" />
                </div>
                <h3 className="text-lg font-bold text-gray-900">No Active Licensed Modules Found</h3>
                <p className="text-xs text-gray-500 max-w-md mx-auto">
                  Downloads are protected by HostNeko licensing system. Please purchase a license plan or activate a free trial to download files.
                </p>
                <Link
                  href="/shop"
                  className="inline-flex items-center gap-2 px-6 py-3 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs shadow-md transition"
                >
                  <ShoppingCart className="w-4 h-4" />
                  <span>Browse Modules & Plans</span>
                </Link>
              </div>
            ) : (
              <div className="space-y-4">
                {activeLicenses.map((lic) => {
                  const fileName = `${lic.product_slug || 'module'}-v1.2.0.zip`;
                  return (
                    <div
                      key={lic.id}
                      className="bg-white rounded-3xl p-6 shadow-sm border border-gray-100 flex flex-col sm:flex-row sm:items-center justify-between gap-4"
                    >
                      <div className="flex items-center gap-4">
                        <div className="w-12 h-12 rounded-2xl bg-indigo-50 text-indigo-600 flex items-center justify-center shrink-0">
                          <FileArchive className="w-6 h-6" />
                        </div>
                        <div>
                          <div className="flex items-center gap-2">
                            <span className="text-[10px] font-extrabold uppercase px-2 py-0.5 bg-emerald-100 text-emerald-700 rounded">
                              {lic.status === 'trial' ? 'Trial License' : 'Active License'}
                            </span>
                            <span className="text-xs font-mono text-gray-400">
                              Key: {lic.license_key}
                            </span>
                          </div>
                          <h3 className="font-extrabold text-base text-gray-900 mt-0.5">
                            {lic.product_title}
                          </h3>
                          <p className="text-xs text-gray-400">
                            Bound: {lic.bound_domain || 'Unbound (Auto on first use)'} &bull; Expires:{' '}
                            {lic.expires_at ? new Date(lic.expires_at).toLocaleDateString() : 'Lifetime'}
                          </p>
                        </div>
                      </div>

                      <div className="flex items-center gap-3">
                        <Link
                          href={`/product/${lic.product_id}/documentation`}
                          className="px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold rounded-xl text-xs flex items-center gap-1.5 transition"
                        >
                          <BookOpen className="w-3.5 h-3.5" />
                          <span>Docs</span>
                        </Link>

                        <a
                          href={`/downloads/${fileName}`}
                          download
                          className="px-5 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-xl text-xs flex items-center gap-2 shadow-md shadow-emerald-600/20 transition active:scale-95"
                        >
                          <Download className="w-4 h-4" />
                          <span>Download ZIP</span>
                        </a>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
