import * as React from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { MobileHeader, BottomNav } from 'components/mobile';
import { isOnline, getPendingPlants, getPendingTransport, clearCachedPlants } from 'lib/mobile/offline';
import { getPWAStatus, promptInstall, clearCaches } from 'lib/mobile/pwa';

interface ProfileStats {
  plantsRegistered: number;
  co2Saved: number;
  foodMiles: number;
  generation: number;
}

export default function ProfilePage() {
  const [online, setOnline] = React.useState(true);
  const [pwaStatus, setPwaStatus] = React.useState(() => getPWAStatus());
  const [pendingSync, setPendingSync] = React.useState({ plants: 0, transport: 0 });
  const [stats] = React.useState<ProfileStats>({
    plantsRegistered: 24,
    co2Saved: 12.5,
    foodMiles: 156,
    generation: 3,
  });

  React.useEffect(() => {
    setOnline(isOnline());

    const handleOnline = () => {
      setOnline(true);
      setPwaStatus(getPWAStatus());
    };
    const handleOffline = () => setOnline(false);

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    // Load pending items count
    const loadPending = async () => {
      const plants = await getPendingPlants();
      const transport = await getPendingTransport();
      setPendingSync({ plants: plants.length, transport: transport.length });
    };
    loadPending();

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  const handleInstall = async () => {
    const success = await promptInstall();
    if (success) {
      setPwaStatus(getPWAStatus());
    }
  };

  const handleClearCache = async () => {
    if (confirm('Are you sure you want to clear all cached data?')) {
      await clearCaches();
      await clearCachedPlants();
      alert('Cache cleared successfully');
    }
  };

  return (
    <>
      <Head>
        <title>Profile - LocalGreenChain</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
      </Head>

      <div className="min-h-screen bg-gray-50 pb-24 md:hidden">
        <MobileHeader title="Profile" />

        <div className="pt-14 p-4 space-y-6">
          {/* Profile header */}
          <section className="bg-white rounded-2xl p-6 shadow-sm">
            <div className="flex items-center space-x-4">
              <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-8 w-8 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                </svg>
              </div>
              <div>
                <h2 className="text-lg font-semibold text-gray-900">Local Grower</h2>
                <p className="text-sm text-gray-500">Member since 2024</p>
                <div className="flex items-center mt-1">
                  <div className={`w-2 h-2 rounded-full ${online ? 'bg-green-500' : 'bg-amber-500'} mr-2`} />
                  <span className="text-xs text-gray-500">{online ? 'Online' : 'Offline'}</span>
                </div>
              </div>
            </div>
          </section>

          {/* Stats */}
          <section>
            <h3 className="text-sm font-medium text-gray-500 uppercase tracking-wide mb-3">Your Stats</h3>
            <div className="grid grid-cols-2 gap-3">
              <div className="bg-white rounded-xl p-4 shadow-sm">
                <p className="text-2xl font-bold text-gray-900">{stats.plantsRegistered}</p>
                <p className="text-sm text-gray-500">Plants Registered</p>
              </div>
              <div className="bg-white rounded-xl p-4 shadow-sm">
                <p className="text-2xl font-bold text-gray-900">{stats.co2Saved} kg</p>
                <p className="text-sm text-gray-500">CO2 Saved</p>
              </div>
              <div className="bg-white rounded-xl p-4 shadow-sm">
                <p className="text-2xl font-bold text-gray-900">{stats.foodMiles}</p>
                <p className="text-sm text-gray-500">Food Miles Tracked</p>
              </div>
              <div className="bg-white rounded-xl p-4 shadow-sm">
                <p className="text-2xl font-bold text-gray-900">Gen {stats.generation}</p>
                <p className="text-sm text-gray-500">Max Generation</p>
              </div>
            </div>
          </section>

          {/* Pending sync */}
          {(pendingSync.plants > 0 || pendingSync.transport > 0) && (
            <section className="bg-amber-50 border border-amber-200 rounded-xl p-4">
              <div className="flex items-start space-x-3">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 text-amber-600 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                <div>
                  <p className="font-medium text-amber-800">Pending Sync</p>
                  <p className="text-sm text-amber-700 mt-1">
                    {pendingSync.plants} plants and {pendingSync.transport} transport events will sync when you're online.
                  </p>
                </div>
              </div>
            </section>
          )}

          {/* App settings */}
          <section>
            <h3 className="text-sm font-medium text-gray-500 uppercase tracking-wide mb-3">App Settings</h3>
            <div className="bg-white rounded-xl shadow-sm divide-y divide-gray-100">
              {/* Install PWA */}
              {!pwaStatus.isInstalled && pwaStatus.canInstall && (
                <button
                  onClick={handleInstall}
                  className="w-full flex items-center justify-between p-4 hover:bg-gray-50"
                >
                  <div className="flex items-center space-x-3">
                    <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                      <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                      </svg>
                    </div>
                    <div className="text-left">
                      <p className="font-medium text-gray-900">Install App</p>
                      <p className="text-sm text-gray-500">Add to home screen for quick access</p>
                    </div>
                  </div>
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </button>
              )}

              {/* Notifications */}
              <Link href="/m/settings/notifications">
                <a className="flex items-center justify-between p-4 hover:bg-gray-50">
                  <div className="flex items-center space-x-3">
                    <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                      <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
                      </svg>
                    </div>
                    <div className="text-left">
                      <p className="font-medium text-gray-900">Notifications</p>
                      <p className="text-sm text-gray-500">Manage push notifications</p>
                    </div>
                  </div>
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </a>
              </Link>

              {/* Privacy */}
              <Link href="/m/settings/privacy">
                <a className="flex items-center justify-between p-4 hover:bg-gray-50">
                  <div className="flex items-center space-x-3">
                    <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                      <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                      </svg>
                    </div>
                    <div className="text-left">
                      <p className="font-medium text-gray-900">Privacy</p>
                      <p className="text-sm text-gray-500">Location, data sharing</p>
                    </div>
                  </div>
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </a>
              </Link>

              {/* Clear cache */}
              <button
                onClick={handleClearCache}
                className="w-full flex items-center justify-between p-4 hover:bg-gray-50"
              >
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-red-100 rounded-lg flex items-center justify-center">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </div>
                  <div className="text-left">
                    <p className="font-medium text-gray-900">Clear Cache</p>
                    <p className="text-sm text-gray-500">Free up storage space</p>
                  </div>
                </div>
              </button>
            </div>
          </section>

          {/* About */}
          <section>
            <h3 className="text-sm font-medium text-gray-500 uppercase tracking-wide mb-3">About</h3>
            <div className="bg-white rounded-xl shadow-sm divide-y divide-gray-100">
              <div className="flex items-center justify-between p-4">
                <span className="text-gray-600">Version</span>
                <span className="text-gray-900">1.0.0</span>
              </div>
              <div className="flex items-center justify-between p-4">
                <span className="text-gray-600">App Mode</span>
                <span className="text-gray-900">{pwaStatus.isStandalone ? 'Standalone' : 'Browser'}</span>
              </div>
              <Link href="/">
                <a className="flex items-center justify-between p-4 hover:bg-gray-50">
                  <span className="text-gray-600">Switch to Desktop</span>
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </a>
              </Link>
            </div>
          </section>
        </div>

        <BottomNav />
      </div>
    </>
  );
}
