'use client';

import React, { useState } from 'react';
import { useStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';
import {
  User,
  Mail,
  Phone,
  Lock,
  Globe,
  Save,
  Loader2,
  CheckCircle2,
  Eye,
  EyeOff,
  Pencil,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { useToast } from '@/hooks/use-toast';

export default function ClientProfile() {
  const currentUser = useStore((s) => s.currentUser);
  const setUser = useStore((s) => s.setUser);
  const language = useStore((s) => s.language);
  const setLanguage = useStore((s) => s.setLanguage);
  const { t } = useTranslation();
  const { toast } = useToast();

  const [isEditing, setIsEditing] = useState(false);
  const [isChangingPassword, setIsChangingPassword] = useState(false);
  const [saving, setSaving] = useState(false);

  // Profile form state
  const [name, setName] = useState(currentUser?.name || '');
  const [phone, setPhone] = useState(currentUser?.phone || '');
  const [email, setEmail] = useState(currentUser?.email || '');

  // Password form state
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);

  const userInitials = currentUser?.name
    ? currentUser.name
        .split(' ')
        .map((n) => n[0])
        .join('')
        .toUpperCase()
        .slice(0, 2)
    : 'U';

  const handleSaveProfile = async () => {
    if (!currentUser) return;
    if (!name.trim()) {
      toast({ title: 'Error', description: 'Name is required', variant: 'destructive' });
      return;
    }
    if (!email.trim()) {
      toast({ title: 'Error', description: 'Email is required', variant: 'destructive' });
      return;
    }

    setSaving(true);
    try {
      const res = await fetch('/api/client/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: currentUser.id,
          name: name.trim(),
          phone: phone.trim(),
          email: email.trim(),
          language,
        }),
      });

      const data = await res.json();

      if (res.ok) {
        setUser({
          ...currentUser,
          name: data.user.name,
          phone: data.user.phone,
          email: data.user.email,
        });
        setIsEditing(false);
        toast({
          title: t.messages.success.profileUpdated,
          description: undefined,
        });
      } else {
        toast({
          title: 'Error',
          description: data.error || t.messages.error.updateFailed,
          variant: 'destructive',
        });
      }
    } catch {
      toast({
        title: 'Error',
        description: t.messages.error.networkError,
        variant: 'destructive',
      });
    } finally {
      setSaving(false);
    }
  };

  const handleChangePassword = async () => {
    if (!currentUser) return;

    if (!currentPassword || !newPassword || !confirmPassword) {
      toast({ title: 'Error', description: 'All password fields are required', variant: 'destructive' });
      return;
    }

    if (newPassword.length < 6) {
      toast({ title: 'Error', description: 'Password must be at least 6 characters', variant: 'destructive' });
      return;
    }

    if (newPassword !== confirmPassword) {
      toast({ title: 'Error', description: t.form.passwordMismatch, variant: 'destructive' });
      return;
    }

    setSaving(true);
    try {
      const res = await fetch('/api/client/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: currentUser.id,
          currentPassword,
          newPassword,
        }),
      });

      const data = await res.json();

      if (res.ok) {
        setCurrentPassword('');
        setNewPassword('');
        setConfirmPassword('');
        setIsChangingPassword(false);
        toast({
          title: t.messages.success.passwordChanged,
        });
      } else {
        toast({
          title: 'Error',
          description: data.error || t.messages.error.updateFailed,
          variant: 'destructive',
        });
      }
    } catch {
      toast({
        title: 'Error',
        description: t.messages.error.networkError,
        variant: 'destructive',
      });
    } finally {
      setSaving(false);
    }
  };

  const handleLanguageChange = async (newLang: 'en' | 'bn') => {
    setLanguage(newLang);
    if (currentUser) {
      try {
        await fetch('/api/client/profile', {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            userId: currentUser.id,
            language: newLang,
          }),
        });
      } catch {
        // Language change in UI is already done, silently fail for API
      }
    }
  };

  const cancelEditing = () => {
    setIsEditing(false);
    setName(currentUser?.name || '');
    setPhone(currentUser?.phone || '');
    setEmail(currentUser?.email || '');
  };

  const cancelPasswordChange = () => {
    setIsChangingPassword(false);
    setCurrentPassword('');
    setNewPassword('');
    setConfirmPassword('');
  };

  return (
    <div className="space-y-6 max-w-2xl mx-auto animate-fade-in">
      {/* Header */}
      <div>
        <h2 className="text-2xl font-bold text-emerald-800">{t.nav.profile}</h2>
        <p className="text-sm text-muted-foreground mt-1">
          Manage your account settings
        </p>
      </div>

      {/* Profile Card */}
      <Card className="border-emerald-100 shadow-sm overflow-hidden">
        <div className="h-24 bg-gradient-to-r from-emerald-400 to-emerald-600" />
        <CardContent className="p-6 -mt-10">
          <div className="flex flex-col sm:flex-row items-start sm:items-end gap-4">
            <Avatar className="w-20 h-20 border-4 border-white shadow-lg">
              <AvatarFallback className="bg-emerald-500 text-white text-xl font-bold">
                {userInitials}
              </AvatarFallback>
            </Avatar>
            <div className="flex-1 min-w-0">
              <h3 className="text-xl font-bold text-emerald-800 truncate">
                {currentUser?.name}
              </h3>
              <div className="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-3 mt-1">
                <span className="flex items-center gap-1.5 text-sm text-muted-foreground">
                  <Mail className="w-3.5 h-3.5" />
                  {currentUser?.email}
                </span>
                {currentUser?.phone && (
                  <span className="flex items-center gap-1.5 text-sm text-muted-foreground">
                    <Phone className="w-3.5 h-3.5" />
                    {currentUser.phone}
                  </span>
                )}
              </div>
            </div>
            <Badge variant="outline" className="bg-emerald-50 text-emerald-700 border-emerald-200">
              {currentUser?.role === 'user' ? t.roles.user : currentUser?.role}
            </Badge>
          </div>
        </CardContent>
      </Card>

      {/* Edit Profile Section */}
      <Card className="border-emerald-100 shadow-sm">
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg flex items-center gap-2 text-emerald-800">
              <User className="w-5 h-5 text-emerald-500" />
              {t.form.name}
            </CardTitle>
            {!isEditing && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setIsEditing(true)}
                className="text-emerald-600 hover:bg-emerald-50"
              >
                <Pencil className="w-4 h-4 mr-1" />
                {t.actions.edit}
              </Button>
            )}
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {isEditing ? (
            <>
              <div className="space-y-2">
                <Label htmlFor="name" className="text-emerald-700">
                  {t.form.name} *
                </Label>
                <Input
                  id="name"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  className="border-emerald-200 focus:border-emerald-400 focus:ring-emerald-400"
                  placeholder="Enter your name"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="email" className="text-emerald-700">
                  {t.form.email} *
                </Label>
                <Input
                  id="email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="border-emerald-200 focus:border-emerald-400 focus:ring-emerald-400"
                  placeholder="Enter your email"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="phone" className="text-emerald-700">
                  {t.form.phone}
                </Label>
                <Input
                  id="phone"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  className="border-emerald-200 focus:border-emerald-400 focus:ring-emerald-400"
                  placeholder="Enter your phone number"
                />
              </div>
              <div className="flex items-center gap-2 pt-2">
                <Button
                  onClick={handleSaveProfile}
                  disabled={saving}
                  className="bg-emerald-600 hover:bg-emerald-700 text-white"
                >
                  {saving ? (
                    <Loader2 className="w-4 h-4 mr-1 animate-spin" />
                  ) : (
                    <Save className="w-4 h-4 mr-1" />
                  )}
                  {t.actions.save}
                </Button>
                <Button
                  variant="outline"
                  onClick={cancelEditing}
                  className="border-emerald-200 text-emerald-700"
                >
                  {t.actions.cancel}
                </Button>
              </div>
            </>
          ) : (
            <div className="space-y-3">
              <div className="flex items-center gap-3 p-3 bg-emerald-50/50 rounded-lg">
                <Mail className="w-4 h-4 text-emerald-500" />
                <div>
                  <p className="text-xs text-muted-foreground">{t.form.email}</p>
                  <p className="text-sm font-medium">{currentUser?.email}</p>
                </div>
              </div>
              <div className="flex items-center gap-3 p-3 bg-emerald-50/50 rounded-lg">
                <Phone className="w-4 h-4 text-emerald-500" />
                <div>
                  <p className="text-xs text-muted-foreground">{t.form.phone}</p>
                  <p className="text-sm font-medium">{currentUser?.phone || 'Not set'}</p>
                </div>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Change Password Section */}
      <Card className="border-emerald-100 shadow-sm">
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg flex items-center gap-2 text-emerald-800">
              <Lock className="w-5 h-5 text-emerald-500" />
              {t.settings.changePassword}
            </CardTitle>
            {!isChangingPassword && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setIsChangingPassword(true)}
                className="text-emerald-600 hover:bg-emerald-50"
              >
                <Pencil className="w-4 h-4 mr-1" />
                {t.actions.edit}
              </Button>
            )}
          </div>
        </CardHeader>
        <CardContent>
          {isChangingPassword ? (
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="currentPassword" className="text-emerald-700">
                  Current Password *
                </Label>
                <div className="relative">
                  <Input
                    id="currentPassword"
                    type={showCurrentPassword ? 'text' : 'password'}
                    value={currentPassword}
                    onChange={(e) => setCurrentPassword(e.target.value)}
                    className="border-emerald-200 focus:border-emerald-400 focus:ring-emerald-400 pr-10"
                    placeholder="Enter current password"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7 p-0 text-gray-400"
                    onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                  >
                    {showCurrentPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </Button>
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="newPassword" className="text-emerald-700">
                  New Password *
                </Label>
                <div className="relative">
                  <Input
                    id="newPassword"
                    type={showNewPassword ? 'text' : 'password'}
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    className="border-emerald-200 focus:border-emerald-400 focus:ring-emerald-400 pr-10"
                    placeholder="Enter new password (min. 6 characters)"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7 p-0 text-gray-400"
                    onClick={() => setShowNewPassword(!showNewPassword)}
                  >
                    {showNewPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </Button>
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="confirmPassword" className="text-emerald-700">
                  {t.form.confirmPassword} *
                </Label>
                <Input
                  id="confirmPassword"
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  className="border-emerald-200 focus:border-emerald-400 focus:ring-emerald-400"
                  placeholder="Confirm new password"
                />
              </div>
              <div className="flex items-center gap-2 pt-2">
                <Button
                  onClick={handleChangePassword}
                  disabled={saving}
                  className="bg-emerald-600 hover:bg-emerald-700 text-white"
                >
                  {saving ? (
                    <Loader2 className="w-4 h-4 mr-1 animate-spin" />
                  ) : (
                    <CheckCircle2 className="w-4 h-4 mr-1" />
                  )}
                  {t.settings.changePassword}
                </Button>
                <Button
                  variant="outline"
                  onClick={cancelPasswordChange}
                  className="border-emerald-200 text-emerald-700"
                >
                  {t.actions.cancel}
                </Button>
              </div>
            </div>
          ) : (
            <div className="flex items-center gap-3 p-3 bg-emerald-50/50 rounded-lg">
              <Lock className="w-4 h-4 text-emerald-500" />
              <p className="text-sm text-muted-foreground">
                Password last changed recently
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Language Preference */}
      <Card className="border-emerald-100 shadow-sm">
        <CardHeader className="pb-3">
          <CardTitle className="text-lg flex items-center gap-2 text-emerald-800">
            <Globe className="w-5 h-5 text-emerald-500" />
            {t.settings.language}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex gap-3">
            <Button
              variant={language === 'en' ? 'default' : 'outline'}
              onClick={() => handleLanguageChange('en')}
              className={
                language === 'en'
                  ? 'bg-emerald-600 hover:bg-emerald-700 text-white'
                  : 'border-emerald-200 text-emerald-700 hover:bg-emerald-50'
              }
            >
              🇬🇧 English
            </Button>
            <Button
              variant={language === 'bn' ? 'default' : 'outline'}
              onClick={() => handleLanguageChange('bn')}
              className={
                language === 'bn'
                  ? 'bg-emerald-600 hover:bg-emerald-700 text-white'
                  : 'border-emerald-200 text-emerald-700 hover:bg-emerald-50'
              }
            >
              🇧🇩 বাংলা
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
