'use client';

import React, { useState, useEffect } from 'react';
import { useAuth } from '@/context/auth-context';
import { apiRequest } from '@/lib/api';
import {
  User,
  Mail,
  Phone,
  Wallet,
  Lock,
  Shield,
  CheckCircle,
  AlertCircle,
  Calendar,
} from 'lucide-react';

export default function StoreProfilePage() {
  const { user, updateUser } = useAuth();

  // Profile fields state
  const [businessName, setBusinessName] = useState(user?.name || '');
  const [sellerPhone, setSellerPhone] = useState(user?.phone || '');
  const [walletAddress, setWalletAddress] = useState(user?.walletAddress || '');
  
  // Security fields state
  const [oldPassword, setOldPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  // Status states
  const [profileSaving, setProfileSaving] = useState(false);
  const [passwordSaving, setPasswordSaving] = useState(false);
  const [profileMessage, setProfileMessage] = useState<{ success: boolean; text: string } | null>(null);
  const [passwordMessage, setPasswordMessage] = useState<{ success: boolean; text: string } | null>(null);

  // Sync state if user changes in context
  useEffect(() => {
    if (user) {
      setBusinessName(user.name);
      setSellerPhone(user.phone || '');
      setWalletAddress(user.walletAddress || '');
    }
  }, [user]);

  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    if (profileSaving || !user) return;
    
    setProfileSaving(true);
    setProfileMessage(null);

    try {
      const res = await apiRequest('api/auth/profile', 'POST', {
        name: businessName,
        contactPhone: sellerPhone,
        walletAddress: walletAddress,
      });

      if (res.success && res.business) {
        updateUser(res.business);
        setProfileMessage({ success: true, text: 'Store profile updated successfully!' });
      } else {
        throw new Error(res.message || 'Failed to update profile');
      }
    } catch (err: any) {
      setProfileMessage({ success: false, text: err.message || 'Error updating profile' });
    } finally {
      setProfileSaving(false);
    }
  };

  const handleUpdatePassword = async (e: React.FormEvent) => {
    e.preventDefault();
    if (passwordSaving) return;

    if (newPassword !== confirmPassword) {
      setPasswordMessage({ success: false, text: 'New passwords do not match' });
      return;
    }

    if (newPassword.length < 6) {
      setPasswordMessage({ success: false, text: 'New password must be at least 6 characters long' });
      return;
    }

    setPasswordSaving(true);
    setPasswordMessage(null);

    try {
      const res = await apiRequest('api/auth/change-password', 'POST', {
        oldPassword,
        newPassword,
      });

      if (res.success) {
        setPasswordMessage({ success: true, text: 'Password changed successfully!' });
        setOldPassword('');
        setNewPassword('');
        setConfirmPassword('');
      } else {
        throw new Error(res.message || 'Failed to update password');
      }
    } catch (err: any) {
      setPasswordMessage({ success: false, text: err.message || 'Error updating password' });
    } finally {
      setPasswordSaving(false);
    }
  };

  const formattedDate = user?.createdAt 
    ? new Date(user.createdAt).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })
    : 'N/A';

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-3xl font-extrabold tracking-tight text-white Outfit">
          Store Profile & Settings
        </h1>
        <p className="text-sm text-gray-400 mt-1">
          Manage your public business details, payouts wallet, and security credentials.
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
        {/* Left Column: Edit Panels */}
        <div className="lg:col-span-8 space-y-8">
          
          {/* Business Details Card */}
          <div className="glass-panel rounded-2xl p-6 space-y-6 relative overflow-hidden">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-xl bg-emerald-500/10 flex items-center justify-center border border-emerald-500/20">
                <User className="h-5 w-5 text-emerald-400" />
              </div>
              <div>
                <h3 className="font-bold text-white text-lg font-sans">Business Details</h3>
                <p className="text-xs text-gray-500 mt-0.5">Public information used in receipts and WhatsApp chats</p>
              </div>
            </div>

            <form onSubmit={handleUpdateProfile} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">Store / Business Name</label>
                  <input
                    type="text"
                    value={businessName}
                    onChange={(e) => setBusinessName(e.target.value)}
                    required
                    className="w-full glass-input px-4 py-2.5 text-sm outline-none focus:border-emerald-500"
                    placeholder="Enter store name"
                  />
                </div>

                <div>
                  <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">Seller WhatsApp Phone</label>
                  <input
                    type="text"
                    value={sellerPhone}
                    onChange={(e) => setSellerPhone(e.target.value)}
                    className="w-full glass-input px-4 py-2.5 text-sm outline-none focus:border-emerald-500"
                    placeholder="e.g. +263777777777"
                  />
                  <p className="text-[10px] text-gray-500 mt-1">Number where order & payment notifications are received</p>
                </div>
              </div>

              <div>
                <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">Payout Wallet / EcoCash / Paynow Address</label>
                <input
                  type="text"
                  value={walletAddress}
                  onChange={(e) => setWalletAddress(e.target.value)}
                  className="w-full glass-input px-4 py-2.5 text-sm outline-none focus:border-emerald-500"
                  placeholder="Enter wallet address or Ecocash phone number"
                />
              </div>

              {profileMessage && (
                <div className={`p-3 rounded-lg text-xs flex gap-2 items-start ${
                  profileMessage.success
                    ? 'bg-emerald-500/10 border border-emerald-500/20 text-emerald-400'
                    : 'bg-red-500/10 border border-red-500/20 text-red-400'
                }`}>
                  {profileMessage.success ? <CheckCircle className="h-4 w-4 shrink-0 mt-0.5" /> : <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />}
                  <span>{profileMessage.text}</span>
                </div>
              )}

              <div className="flex justify-end pt-2">
                <button
                  type="submit"
                  disabled={profileSaving}
                  className="px-6 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold py-2.5 rounded-lg text-xs transition-all cursor-pointer shadow-md shadow-emerald-500/10 disabled:opacity-50"
                >
                  {profileSaving ? 'Saving Changes...' : 'Save Profile Changes'}
                </button>
              </div>
            </form>
          </div>

          {/* Security / Password Card */}
          <div className="glass-panel rounded-2xl p-6 space-y-6 relative overflow-hidden">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-xl bg-emerald-500/10 flex items-center justify-center border border-emerald-500/20">
                <Lock className="h-5 w-5 text-emerald-400" />
              </div>
              <div>
                <h3 className="font-bold text-white text-lg font-sans">Security Settings</h3>
                <p className="text-xs text-gray-500 mt-0.5">Change your account login credentials</p>
              </div>
            </div>

            <form onSubmit={handleUpdatePassword} className="space-y-4">
              <div>
                <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">Current Password</label>
                <input
                  type="password"
                  value={oldPassword}
                  onChange={(e) => setOldPassword(e.target.value)}
                  required
                  className="w-full glass-input px-4 py-2.5 text-sm outline-none focus:border-emerald-500"
                  placeholder="••••••••"
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">New Password</label>
                  <input
                    type="password"
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    required
                    className="w-full glass-input px-4 py-2.5 text-sm outline-none focus:border-emerald-500"
                    placeholder="••••••••"
                  />
                  <p className="text-[10px] text-gray-500 mt-1">Minimum 6 characters</p>
                </div>

                <div>
                  <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">Confirm New Password</label>
                  <input
                    type="password"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    required
                    className="w-full glass-input px-4 py-2.5 text-sm outline-none focus:border-emerald-500"
                    placeholder="••••••••"
                  />
                </div>
              </div>

              {passwordMessage && (
                <div className={`p-3 rounded-lg text-xs flex gap-2 items-start ${
                  passwordMessage.success
                    ? 'bg-emerald-500/10 border border-emerald-500/20 text-emerald-400'
                    : 'bg-red-500/10 border border-red-500/20 text-red-400'
                }`}>
                  {passwordMessage.success ? <CheckCircle className="h-4 w-4 shrink-0 mt-0.5" /> : <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />}
                  <span>{passwordMessage.text}</span>
                </div>
              )}

              <div className="flex justify-end pt-2">
                <button
                  type="submit"
                  disabled={passwordSaving}
                  className="px-6 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold py-2.5 rounded-lg text-xs transition-all cursor-pointer shadow-md shadow-emerald-500/10 disabled:opacity-50"
                >
                  {passwordSaving ? 'Updating Password...' : 'Update Password'}
                </button>
              </div>
            </form>
          </div>

        </div>

        {/* Right Column: Information & Metadata */}
        <div className="lg:col-span-4 space-y-6">
          
          {/* Account Details Card */}
          <div className="glass-panel rounded-2xl p-6 space-y-6">
            <h3 className="font-bold text-white text-base font-sans">Account Information</h3>
            
            <div className="space-y-4">
              <div className="flex items-center gap-3 bg-white/2 p-3 rounded-xl border border-white/5">
                <Mail className="h-4 w-4 text-gray-400 shrink-0" />
                <div className="min-w-0">
                  <span className="block text-[10px] font-bold text-gray-500 uppercase tracking-wider">Email Address</span>
                  <span className="text-xs text-white truncate block">{user?.email}</span>
                </div>
              </div>

              <div className="flex items-center gap-3 bg-white/2 p-3 rounded-xl border border-white/5">
                <Shield className={`h-4 w-4 shrink-0 ${user?.subscriptionStatus === 'UNSUBSCRIBED' || user?.subscriptionStatus === 'EXPIRED' ? 'text-amber-400' : 'text-emerald-400'}`} />
                <div>
                  <span className="block text-[10px] font-bold text-gray-500 uppercase tracking-wider">Subscription Plan</span>
                  {user?.subscriptionStatus === 'UNSUBSCRIBED' || user?.subscriptionStatus === 'EXPIRED' ? (
                    <span className="inline-flex items-center mt-1 px-2 py-0.5 rounded-md text-[10px] font-bold bg-amber-500/10 text-amber-400 border border-amber-500/20 uppercase tracking-wide">
                      Not Activated
                    </span>
                  ) : user?.subscriptionStatus === 'TRIAL' ? (
                    <span className="inline-flex items-center mt-1 px-2 py-0.5 rounded-md text-[10px] font-bold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 uppercase tracking-wide">
                      14-Day Free Trial
                    </span>
                  ) : (
                    <span className="inline-flex items-center mt-1 px-2 py-0.5 rounded-md text-[10px] font-bold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 uppercase tracking-wide">
                      {user?.subscriptionPlan || 'STARTER'}
                    </span>
                  )}
                </div>
              </div>

              <div className="flex items-center gap-3 bg-white/2 p-3 rounded-xl border border-white/5">
                <Calendar className="h-4 w-4 text-gray-400 shrink-0" />
                <div>
                  <span className="block text-[10px] font-bold text-gray-500 uppercase tracking-wider">Member Since</span>
                  <span className="text-xs text-white">{formattedDate}</span>
                </div>
              </div>

              <div className="flex items-center gap-3 bg-white/2 p-3 rounded-xl border border-white/5">
                <div>
                  <span className="block text-[10px] font-bold text-gray-500 uppercase tracking-wider">Account Status</span>
                  {user?.subscriptionStatus === 'UNSUBSCRIBED' || user?.subscriptionStatus === 'EXPIRED' ? (
                    <span className="text-xs text-emerald-400 font-bold uppercase">Active</span>
                  ) : (
                    <span className="text-xs text-emerald-400 font-bold uppercase">Active</span>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* Guide Tips Card */}
          <div className="glass-panel rounded-2xl p-6 bg-gradient-to-br from-emerald-500/5 to-transparent space-y-4">
            <h4 className="font-bold text-white text-sm font-sans">Profile Guide</h4>
            <div className="text-xs text-gray-400 space-y-3 leading-relaxed">
              <p>
                <strong>Business Name:</strong> This is displayed to your customers at the top of the WhatsApp interactive shopping menus.
              </p>
              <p>
                <strong>Seller WhatsApp Number:</strong> This number receives checkout receipt details and customer requests when a payment is processed.
              </p>
              <p>
                <strong>Wallet / Payout address:</strong> Provide your merchant EcoCash number or billing account reference here so that gateways like Paynow or PesePay can route ZWL/USD funds to your account directly.
              </p>
            </div>
          </div>

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