import { useState } from 'react';
import { useStudentStore } from '@/stores/studentStore';
import { useUIStore } from '@/stores/uiStore';
import { Avatar, StatusBadge, SkillLevelBadge, ProgressRing, WhatsAppButton, SectionTitle } from '@/components/common';
import { formatDate, formatCurrency, calculateAge } from '@/lib/formatters';
import { Phone, Calendar, User, IndianRupee, MapPin, Pencil, Trash2, Mail, Lock, KeyRound } from 'lucide-react';

export default function StudentDetailScreen() {
  const { selectedStudent, deleteStudent } = useStudentStore();
  const { goBack, navigateTo, showToast } = useUIStore();
  const [showDelete, setShowDelete] = useState(false);
  const [showPasswordReset, setShowPasswordReset] = useState(false);
  const [newPassword, setNewPassword] = useState('');

  const s = selectedStudent;
  if (!s) return null;

  const handleDelete = async () => {
    await deleteStudent(s.id);
    showToast({ type: 'success', message: 'Student removed successfully' });
    goBack();
  };

  const handleResetPassword = async () => {
    const password = newPassword || Math.random().toString(36).slice(-8);
    // In production, this would call the API to update password
    showToast({ type: 'success', message: `Password reset to: ${password}` });
    setNewPassword('');
    setShowPasswordReset(false);
  };

  return (
    <div className="px-4 pt-4 pb-4 space-y-4">
      {/* Profile Header */}
      <div className="bg-white rounded-2xl p-6 card-shadow text-center">
        <Avatar name={s.fullName} size="xl" />
        <h2 className="text-xl font-bold text-gray-900 mt-3">{s.fullName}</h2>
        <p className="text-sm font-medium text-orange-500 mt-1">{s.studentId}</p>
        <div className="flex items-center justify-center gap-2 mt-2">
          <SkillLevelBadge level={s.skillLevel} />
          <StatusBadge status="active" />
        </div>
      </div>

      {/* ===== LOGIN INFO (Admin can see) ===== */}
      <div className="bg-purple-50 rounded-2xl p-4 border border-purple-200">
        <div className="flex items-center gap-2 mb-3">
          <KeyRound className="w-4 h-4 text-purple-500" />
          <h3 className="text-sm font-bold text-purple-700">Login Info (Admin Only)</h3>
        </div>
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Mail className="w-3.5 h-3.5 text-purple-400" />
              <span className="text-xs text-purple-500">Login ID (Email)</span>
            </div>
            <span className="text-sm font-mono font-bold text-purple-700">{s.email || 'Not set'}</span>
          </div>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Lock className="w-3.5 h-3.5 text-purple-400" />
              <span className="text-xs text-purple-500">Password</span>
            </div>
            <span className="text-xs text-gray-400 italic">Hidden (hashed for security)</span>
          </div>
          <p className="text-[10px] text-purple-400 mt-1">Student logs in at: yourwebsite.com/#/student</p>
        </div>
        <button onClick={() => setShowPasswordReset(true)}
          className="mt-3 w-full py-2 bg-purple-500 text-white text-xs font-bold rounded-xl active:scale-[0.98] transition-transform">
          Reset Password
        </button>
      </div>

      {/* Info Grid */}
      <div className="grid grid-cols-2 gap-3">
        {[
          { icon: <Phone className="w-4 h-4" />, label: 'Phone', value: s.phone },
          { icon: <Mail className="w-4 h-4" />, label: 'Email', value: s.email },
          { icon: <MapPin className="w-4 h-4" />, label: 'Address', value: s.address || 'Not set' },
          { icon: <Calendar className="w-4 h-4" />, label: 'Joined', value: formatDate(s.joiningDate) },
          { icon: <User className="w-4 h-4" />, label: 'Age', value: `${s.age || calculateAge(s.dateOfBirth)} years` },
          { icon: <IndianRupee className="w-4 h-4" />, label: 'Monthly Fee', value: formatCurrency(s.monthlyFee) },
        ].map((item, i) => (
          <div key={i} className="bg-white rounded-xl p-3 card-shadow">
            <div className="text-orange-500 mb-1">{item.icon}</div>
            <p className="text-[10px] text-gray-400 uppercase font-medium">{item.label}</p>
            <p className="text-sm font-semibold text-gray-800 mt-0.5">{item.value}</p>
          </div>
        ))}
      </div>

      {/* Fee Status */}
      <div className={`bg-white rounded-2xl p-4 card-shadow ${s.feeStatus === 'due' ? 'border-l-4 border-red-500' : ''}`}>
        <SectionTitle title="Fee Status" action={<StatusBadge status={s.feeStatus || 'pending'} />} />
        <p className="text-2xl font-bold text-gray-900 mt-1">{formatCurrency(s.monthlyFee)}</p>
        <p className="text-xs text-gray-400 mt-1">Monthly fee for {new Date().toLocaleDateString('en-IN', { month: 'long', year: 'numeric' })}</p>
        <button onClick={() => navigateTo('fees')} className="mt-3 w-full py-2.5 border border-orange-500 text-orange-500 font-semibold rounded-xl text-sm active:scale-[0.98] transition-transform">
          Record Payment
        </button>
      </div>

      {/* Attendance */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <SectionTitle title="Attendance" action={<span className="text-xs text-orange-500 font-medium">This Month</span>} />
        <div className="flex items-center gap-4 mt-2">
          <ProgressRing percentage={75} size={64} />
          <div className="flex-1">
            <div className="flex justify-between text-sm">
              <span className="text-gray-500">Present</span>
              <span className="font-semibold text-gray-800">18 days</span>
            </div>
            <div className="flex justify-between text-sm mt-1">
              <span className="text-gray-500">Absent</span>
              <span className="font-semibold text-gray-800">2 days</span>
            </div>
          </div>
        </div>
      </div>

      {/* Action Buttons */}
      <div className="flex items-center justify-center gap-6 pt-2 pb-4">
        <WhatsAppButton phone={s.phone} message={`Hi ${s.fullName}, this is from SkatePro Academy!`} />
        <button onClick={() => { navigateTo('addStudent'); }}
          className="w-14 h-14 rounded-full bg-orange-500 flex items-center justify-center shadow-md active:scale-90 transition-transform">
          <Pencil className="w-5 h-5 text-white" />
        </button>
        <button onClick={() => setShowDelete(true)}
          className="w-14 h-14 rounded-full bg-red-500 flex items-center justify-center shadow-md active:scale-90 transition-transform">
          <Trash2 className="w-5 h-5 text-white" />
        </button>
      </div>

      {/* Password Reset Modal */}
      {showPasswordReset && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center px-6">
          <div className="absolute inset-0 bg-black/50" onClick={() => setShowPasswordReset(false)} />
          <div className="relative bg-white rounded-2xl p-6 max-w-xs w-full animate-scale-in">
            <h3 className="text-lg font-bold text-gray-900 text-center">Reset Password</h3>
            <p className="text-sm text-gray-500 text-center mt-1">{s.fullName} ({s.email})</p>
            <input type="text" value={newPassword} onChange={e => setNewPassword(e.target.value)}
              placeholder="Leave empty for random"
              className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl text-sm mt-4" />
            <button onClick={handleResetPassword}
              className="mt-3 w-full py-3 bg-purple-500 text-white font-bold rounded-xl">
              Reset Password
            </button>
            <button onClick={() => setShowPasswordReset(false)}
              className="mt-2 w-full py-2 text-gray-400 text-sm">Cancel</button>
          </div>
        </div>
      )}

      {/* Delete Confirmation */}
      {showDelete && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center px-6">
          <div className="absolute inset-0 bg-black/50" onClick={() => setShowDelete(false)} />
          <div className="relative bg-white rounded-2xl p-6 max-w-xs w-full text-center animate-scale-in">
            <div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-3">
              <Trash2 className="w-6 h-6 text-red-500" />
            </div>
            <h3 className="text-lg font-bold text-gray-900">Delete Student?</h3>
            <p className="text-sm text-gray-500 mt-1">This action cannot be undone. {s.fullName} will be removed.</p>
            <div className="flex gap-3 mt-5">
              <button onClick={() => setShowDelete(false)} className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm font-semibold text-gray-600">Cancel</button>
              <button onClick={handleDelete} className="flex-1 py-2.5 bg-red-500 text-white rounded-xl text-sm font-semibold">Delete</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
