'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog'
import {
  User,
  Mail,
  Phone,
  MapPin,
  School,
  Award,
  Crown,
  Shield,
  Edit3,
  Camera,
  Loader2,
  Lock,
  Star,
  Calendar,
  CheckCircle,
} from 'lucide-react'
import { BRAND } from '@/lib/constants'

/* ------------------------------------------------------------------ */
/* Types                                                               */
/* ------------------------------------------------------------------ */

interface UserProfile {
  id: string
  email: string
  firstName: string | null
  lastName: string | null
  phone: string | null
  grade: number | null
  gender: string | null
  province: string | null
  city: string | null
  suburb: string | null
  schoolName: string | null
  role: string
  status: string
  points: number
  profilePic: string | null
  assessmentCompleted: boolean
  createdAt: string
  userPremium: {
    plan: string
    startDate: string | null
    expiryDate: string | null
  } | null
  _count: {
    academicResults: number
    chatMessages: number
    tutorSessionsLearner: number
  }
}

/* ------------------------------------------------------------------ */
/* Main Page                                                           */
/* ------------------------------------------------------------------ */

export default function ProfilePage() {
  const [profile, setProfile] = useState<UserProfile | null>(null)
  const [loading, setLoading] = useState(true)
  const [editing, setEditing] = useState(false)
  const [showPasswordDialog, setShowPasswordDialog] = useState(false)
  const [saving, setSaving] = useState(false)

  // Form fields
  const [firstName, setFirstName] = useState('')
  const [lastName, setLastName] = useState('')
  const [phone, setPhone] = useState('')
  const [province, setProvince] = useState('')
  const [city, setCity] = useState('')
  const [suburb, setSuburb] = useState('')
  const [schoolName, setSchoolName] = useState('')

  // Password fields
  const [currentPassword, setCurrentPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')

  useEffect(() => {
    async function fetchProfile() {
      setLoading(true)
      try {
        const res = await fetch('/api/profile?userId=demo-student')
        if (!res.ok) throw new Error('Failed to fetch profile')
        const data = await res.json()
        setProfile(data.user)
        if (data.user) {
          setFirstName(data.user.firstName || '')
          setLastName(data.user.lastName || '')
          setPhone(data.user.phone || '')
          setProvince(data.user.province || '')
          setCity(data.user.city || '')
          setSuburb(data.user.suburb || '')
          setSchoolName(data.user.schoolName || '')
        }
      } catch {
        setProfile(null)
      } finally {
        setLoading(false)
      }
    }
    fetchProfile()
  }, [])

  const handleSave = async () => {
    setSaving(true)
    try {
      const res = await fetch('/api/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: 'demo-student',
          firstName,
          lastName,
          phone,
          province,
          city,
          suburb,
          schoolName,
        }),
      })
      if (!res.ok) throw new Error('Failed to save')
      const data = await res.json()
      setProfile((prev) => prev ? { ...prev, ...data.user } : prev)
      setEditing(false)
    } catch {
      alert('Failed to save profile. Please try again.')
    } finally {
      setSaving(false)
    }
  }

  const handleCancelEdit = () => {
    if (profile) {
      setFirstName(profile.firstName || '')
      setLastName(profile.lastName || '')
      setPhone(profile.phone || '')
      setProvince(profile.province || '')
      setCity(profile.city || '')
      setSuburb(profile.suburb || '')
      setSchoolName(profile.schoolName || '')
    }
    setEditing(false)
  }

  const getInitials = () => {
    const first = profile?.firstName || ''
    const last = profile?.lastName || ''
    return (first[0] || 'S') + (last[0] || '')
  }

  const isPremium = profile?.userPremium?.plan !== 'free'
  const memberSince = profile?.createdAt
    ? new Date(profile.createdAt).toLocaleDateString('en-ZA', { month: 'long', year: 'numeric' })
    : '—'

  if (loading) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div className="flex items-center justify-center py-16">
          <Loader2 className="w-8 h-8 text-[#5b9ebd] animate-spin" />
        </div>
      </div>
    )
  }

  if (!profile) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <Card className="text-center py-12">
          <CardContent>
            <User className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-semibold mb-2">Profile not found</h3>
            <p className="text-gray-500">Unable to load your profile. Please try again.</p>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <div
              className="w-8 h-8 rounded-lg flex items-center justify-center"
              style={{ background: BRAND.colors.primaryGradient }}
            >
              <User className="w-4 h-4 text-white" />
            </div>
            <h1 className="text-2xl font-bold text-gray-900">My Profile</h1>
          </div>
          <p className="text-sm text-gray-500">Manage your personal information</p>
        </div>
        <Button
          onClick={() => (editing ? handleCancelEdit() : setEditing(true))}
          variant={editing ? 'outline' : 'default'}
          className={`rounded-xl ${!editing ? 'text-white' : ''}`}
          style={!editing ? { background: BRAND.colors.primaryGradient } : {}}
        >
          {editing ? (
            <>Cancel</>
          ) : (
            <>
              <Edit3 className="w-4 h-4 mr-2" />
              Edit Profile
            </>
          )}
        </Button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column - Profile Card */}
        <div className="space-y-6">
          {/* Avatar Card */}
          <Card>
            <CardContent className="p-6 text-center">
              <div className="relative inline-block mb-4">
                <div
                  className="w-24 h-24 rounded-full flex items-center justify-center text-white font-bold text-3xl mx-auto"
                  style={{ background: BRAND.colors.primaryGradient }}
                >
                  {profile.profilePic ? (
                    <img
                      src={profile.profilePic}
                      alt="Profile"
                      className="w-full h-full rounded-full object-cover"
                    />
                  ) : (
                    getInitials()
                  )}
                </div>
                <button className="absolute bottom-0 right-0 w-8 h-8 rounded-full bg-white border shadow-sm flex items-center justify-center text-gray-500 hover:text-[#5b9ebd] transition-colors">
                  <Camera className="w-4 h-4" />
                </button>
              </div>
              <h2 className="text-lg font-bold text-gray-900">
                {profile.firstName} {profile.lastName}
              </h2>
              <p className="text-sm text-gray-500">{profile.email}</p>
              {isPremium && (
                <Badge className="mt-2 bg-yellow-100 text-yellow-700 border-yellow-200 hover:bg-yellow-100">
                  <Crown className="w-3 h-3 mr-1" />
                  {profile.userPremium?.plan === 'premium' ? 'Premium' : profile.userPremium?.plan === 'basic' ? 'Basic' : 'Free'}
                </Badge>
              )}
              {!isPremium && (
                <Badge variant="outline" className="mt-2">
                  <Shield className="w-3 h-3 mr-1" />
                  Free Plan
                </Badge>
              )}
            </CardContent>
          </Card>

          {/* Stats Card */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-semibold text-gray-600">Stats</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-xs text-gray-500 flex items-center gap-1.5">
                  <Star className="w-3.5 h-3.5 text-yellow-500" />
                  Points
                </span>
                <span className="text-sm font-bold" style={{ color: BRAND.colors.primaryDark }}>
                  {profile.points}
                </span>
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <span className="text-xs text-gray-500 flex items-center gap-1.5">
                  <Award className="w-3.5 h-3.5" />
                  Results
                </span>
                <span className="text-sm font-semibold">{profile._count.academicResults}</span>
              </div>
              <Separator />
              <div className="flex items-center justify-between">
                <span className="text-xs text-gray-500 flex items-center gap-1.5">
                  <Calendar className="w-3.5 h-3.5" />
                  Member Since
                </span>
                <span className="text-sm font-semibold">{memberSince}</span>
              </div>
            </CardContent>
          </Card>

          {/* Premium Upgrade Card */}
          {!isPremium && (
            <Card className="border-yellow-200 bg-gradient-to-br from-yellow-50 to-orange-50">
              <CardContent className="p-4">
                <div className="flex items-center gap-2 mb-2">
                  <Crown className="w-5 h-5 text-yellow-600" />
                  <h3 className="font-semibold text-sm text-yellow-800">Go Premium</h3>
                </div>
                <p className="text-xs text-yellow-700 mb-3">
                  Unlock AI Coach, competitions, advanced reports, and more!
                </p>
                <Button
                  size="sm"
                  className="w-full rounded-lg text-white text-xs"
                  style={{ background: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)' }}
                >
                  Upgrade Now
                </Button>
              </CardContent>
            </Card>
          )}

          {/* Change Password */}
          <Card>
            <CardContent className="p-4">
              <button
                onClick={() => setShowPasswordDialog(true)}
                className="flex items-center gap-2 text-sm text-gray-600 hover:text-[#5b9ebd] transition-colors w-full"
              >
                <Lock className="w-4 h-4" />
                Change Password
              </button>
            </CardContent>
          </Card>
        </div>

        {/* Right Column - Details */}
        <div className="lg:col-span-2">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base font-semibold">Personal Information</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <Label className="text-xs font-medium text-gray-500 flex items-center gap-1 mb-1.5">
                    <User className="w-3 h-3" /> First Name
                  </Label>
                  {editing ? (
                    <Input value={firstName} onChange={(e) => setFirstName(e.target.value)} className="rounded-lg" />
                  ) : (
                    <p className="text-sm text-gray-900 bg-gray-50 rounded-lg px-3 py-2">
                      {profile.firstName || '—'}
                    </p>
                  )}
                </div>
                <div>
                  <Label className="text-xs font-medium text-gray-500 flex items-center gap-1 mb-1.5">
                    <User className="w-3 h-3" /> Last Name
                  </Label>
                  {editing ? (
                    <Input value={lastName} onChange={(e) => setLastName(e.target.value)} className="rounded-lg" />
                  ) : (
                    <p className="text-sm text-gray-900 bg-gray-50 rounded-lg px-3 py-2">
                      {profile.lastName || '—'}
                    </p>
                  )}
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <Label className="text-xs font-medium text-gray-500 flex items-center gap-1 mb-1.5">
                    <Mail className="w-3 h-3" /> Email
                  </Label>
                  <p className="text-sm text-gray-900 bg-gray-50 rounded-lg px-3 py-2">
                    {profile.email}
                  </p>
                </div>
                <div>
                  <Label className="text-xs font-medium text-gray-500 flex items-center gap-1 mb-1.5">
                    <Phone className="w-3 h-3" /> Phone
                  </Label>
                  {editing ? (
                    <Input value={phone} onChange={(e) => setPhone(e.target.value)} className="rounded-lg" />
                  ) : (
                    <p className="text-sm text-gray-900 bg-gray-50 rounded-lg px-3 py-2">
                      {profile.phone || '—'}
                    </p>
                  )}
                </div>
              </div>

              <Separator />

              <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Location</p>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div>
                  <Label className="text-xs font-medium text-gray-500 flex items-center gap-1 mb-1.5">
                    <MapPin className="w-3 h-3" /> Province
                  </Label>
                  {editing ? (
                    <Select value={province} onValueChange={setProvince}>
                      <SelectTrigger className="rounded-lg">
                        <SelectValue placeholder="Select province" />
                      </SelectTrigger>
                      <SelectContent>
                        {BRAND.provinces.map((p) => (
                          <SelectItem key={p} value={p}>{p}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  ) : (
                    <p className="text-sm text-gray-900 bg-gray-50 rounded-lg px-3 py-2">
                      {profile.province || '—'}
                    </p>
                  )}
                </div>
                <div>
                  <Label className="text-xs font-medium text-gray-500 flex items-center gap-1 mb-1.5">
                    <MapPin className="w-3 h-3" /> City
                  </Label>
                  {editing ? (
                    <Input value={city} onChange={(e) => setCity(e.target.value)} className="rounded-lg" />
                  ) : (
                    <p className="text-sm text-gray-900 bg-gray-50 rounded-lg px-3 py-2">
                      {profile.city || '—'}
                    </p>
                  )}
                </div>
                <div>
                  <Label className="text-xs font-medium text-gray-500 flex items-center gap-1 mb-1.5">
                    <MapPin className="w-3 h-3" /> Suburb
                  </Label>
                  {editing ? (
                    <Input value={suburb} onChange={(e) => setSuburb(e.target.value)} className="rounded-lg" />
                  ) : (
                    <p className="text-sm text-gray-900 bg-gray-50 rounded-lg px-3 py-2">
                      {profile.suburb || '—'}
                    </p>
                  )}
                </div>
              </div>

              <Separator />

              <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Academic</p>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <Label className="text-xs font-medium text-gray-500 flex items-center gap-1 mb-1.5">
                    <School className="w-3 h-3" /> School
                  </Label>
                  {editing ? (
                    <Input value={schoolName} onChange={(e) => setSchoolName(e.target.value)} className="rounded-lg" />
                  ) : (
                    <p className="text-sm text-gray-900 bg-gray-50 rounded-lg px-3 py-2">
                      {profile.schoolName || '—'}
                    </p>
                  )}
                </div>
                <div>
                  <Label className="text-xs font-medium text-gray-500 flex items-center gap-1 mb-1.5">
                    <Award className="w-3 h-3" /> Grade
                  </Label>
                  <p className="text-sm text-gray-900 bg-gray-50 rounded-lg px-3 py-2">
                    {profile.grade ? `Grade ${profile.grade}` : '—'}
                  </p>
                </div>
              </div>

              <Separator />

              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Shield className="w-4 h-4 text-gray-400" />
                  <span className="text-xs text-gray-500">
                    Account Type: <span className="font-medium text-gray-700 capitalize">{profile.role}</span>
                  </span>
                </div>
                <span className="text-xs text-gray-400">
                  Status: <span className="font-medium capitalize text-green-600">{profile.status}</span>
                </span>
              </div>

              {editing && (
                <div className="flex justify-end gap-2 pt-2">
                  <Button variant="outline" onClick={handleCancelEdit} className="rounded-lg">
                    Cancel
                  </Button>
                  <Button
                    onClick={handleSave}
                    disabled={saving}
                    className="rounded-lg text-white"
                    style={{ background: BRAND.colors.primaryGradient }}
                  >
                    {saving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                    <CheckCircle className="w-4 h-4 mr-2" />
                    Save Changes
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Change Password Dialog */}
      <Dialog open={showPasswordDialog} onOpenChange={setShowPasswordDialog}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Change Password</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label className="text-sm font-medium">Current Password</Label>
              <Input type="password" value={currentPassword} onChange={(e) => setCurrentPassword(e.target.value)} className="mt-1 rounded-lg" />
            </div>
            <div>
              <Label className="text-sm font-medium">New Password</Label>
              <Input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} className="mt-1 rounded-lg" />
            </div>
            <div>
              <Label className="text-sm font-medium">Confirm New Password</Label>
              <Input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} className="mt-1 rounded-lg" />
            </div>
          </div>
          <DialogFooter className="gap-2">
            <Button variant="outline" onClick={() => setShowPasswordDialog(false)} className="rounded-lg">
              Cancel
            </Button>
            <Button
              className="rounded-lg text-white"
              style={{ background: BRAND.colors.primaryGradient }}
              onClick={() => {
                if (newPassword !== confirmPassword) {
                  alert('Passwords do not match')
                  return
                }
                alert('Password change feature requires authentication setup.')
                setShowPasswordDialog(false)
              }}
            >
              Update Password
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
