'use client';

import { useEffect, useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useAuthStore } from '@/lib/auth-store';
import { profileApi, type AgentProfile } from '@/lib/profile-api';

const KYC_STATUS_MAP: Record<string, { label: string; variant: 'default' | 'secondary' | 'destructive' | 'outline' }> = {
  NONE: { label: 'Chưa xác minh', variant: 'outline' },
  PENDING: { label: 'Đang chờ duyệt', variant: 'secondary' },
  VERIFIED: { label: 'Đã xác minh', variant: 'default' },
  REJECTED: { label: 'Bị từ chối', variant: 'destructive' },
};

export default function ProfilePage() {
  const { user, fetchProfile } = useAuthStore();
  const [agentProfile, setAgentProfile] = useState<AgentProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const [formData, setFormData] = useState({
    fullName: '',
    email: '',
    phone: '',
  });

  useEffect(() => {
    setLoading(true);
    profileApi
      .getAgentProfile()
      .then((agent) => setAgentProfile(agent))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    if (user) {
      setFormData({
        fullName: user.fullName,
        email: user.email ?? '',
        phone: user.phone,
      });
    }
  }, [user]);

  const handleSave = async () => {
    setSaving(true);
    setError(null);
    setSuccess(null);
    try {
      await profileApi.updateProfile({
        fullName: formData.fullName,
        email: formData.email || undefined,
      });
      await fetchProfile();
      setSuccess('Cập nhật hồ sơ thành công');
      setEditing(false);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Cập nhật thất bại');
    } finally {
      setSaving(false);
    }
  };

  const kycInfo = KYC_STATUS_MAP[user?.kycStatus ?? 'NONE'] ?? { label: 'Chưa xác minh', variant: 'outline' as const };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold">Hồ sơ cá nhân</h1>
        <p className="mt-2 text-muted-foreground">Quản lý thông tin tài khoản của bạn</p>
      </div>

      {error && (
        <div className="rounded-lg border border-red-200 bg-red-50 p-4 text-sm text-red-700">
          {error}
          <button onClick={() => setError(null)} className="ml-2 font-medium underline">
            Đóng
          </button>
        </div>
      )}

      {success && (
        <div className="rounded-lg border border-green-200 bg-green-50 p-4 text-sm text-green-700">
          {success}
          <button onClick={() => setSuccess(null)} className="ml-2 font-medium underline">
            Đóng
          </button>
        </div>
      )}

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Profile info */}
        <Card className="lg:col-span-2">
          <CardHeader className="flex flex-row items-center justify-between">
            <div>
              <CardTitle className="text-lg">Thông tin cá nhân</CardTitle>
              <CardDescription>Thông tin cơ bản trên hồ sơ của bạn</CardDescription>
            </div>
            {!editing && (
              <Button variant="outline" size="sm" onClick={() => setEditing(true)}>
                Chỉnh sửa
              </Button>
            )}
          </CardHeader>
          <CardContent className="space-y-4">
            {loading ? (
              <div className="flex h-32 items-center justify-center text-muted-foreground">
                Đang tải...
              </div>
            ) : (
              <>
                <div className="space-y-2">
                  <Label htmlFor="fullName">Họ và tên</Label>
                  {editing ? (
                    <Input
                      id="fullName"
                      value={formData.fullName}
                      onChange={(e) => setFormData((p) => ({ ...p, fullName: e.target.value }))}
                    />
                  ) : (
                    <p className="rounded-md border bg-muted/50 px-3 py-2 text-sm">
                      {user?.fullName ?? '—'}
                    </p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="phone">Số điện thoại</Label>
                  <p className="rounded-md border bg-muted/50 px-3 py-2 text-sm">
                    {user?.phone ?? '—'}
                  </p>
                  <p className="text-xs text-muted-foreground">
                    Số điện thoại không thể thay đổi
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="email">Email</Label>
                  {editing ? (
                    <Input
                      id="email"
                      type="email"
                      value={formData.email}
                      onChange={(e) => setFormData((p) => ({ ...p, email: e.target.value }))}
                      placeholder="email@example.com"
                    />
                  ) : (
                    <p className="rounded-md border bg-muted/50 px-3 py-2 text-sm">
                      {user?.email ?? 'Chưa cập nhật'}
                    </p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label>Vai trò</Label>
                  <p className="rounded-md border bg-muted/50 px-3 py-2 text-sm">
                    {user?.role === 'AGENT' ? 'Môi giới' : user?.role === 'ADMIN' ? 'Quản trị viên' : user?.role === 'SELLER' ? 'Người bán' : 'Người mua'}
                  </p>
                </div>

                {editing && (
                  <div className="flex gap-2 pt-2">
                    <Button onClick={handleSave} disabled={saving}>
                      {saving ? 'Đang lưu...' : 'Lưu thay đổi'}
                    </Button>
                    <Button
                      variant="outline"
                      onClick={() => {
                        setEditing(false);
                        if (user) {
                          setFormData({
                            fullName: user.fullName,
                            email: user.email ?? '',
                            phone: user.phone,
                          });
                        }
                      }}
                    >
                      Hủy
                    </Button>
                  </div>
                )}
              </>
            )}
          </CardContent>
        </Card>

        {/* Status sidebar */}
        <div className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Trạng thái tài khoản</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Tài khoản</span>
                <Badge variant={user?.isActive ? 'default' : 'destructive'}>
                  {user?.isActive ? 'Hoạt động' : 'Bị khóa'}
                </Badge>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Xác minh KYC</span>
                <Badge variant={kycInfo.variant}>{kycInfo.label}</Badge>
              </div>
              {user?.kycStatus !== 'VERIFIED' && (
                <a href="/dashboard/kyc">
                  <Button variant="outline" size="sm" className="mt-2 w-full">
                    {user?.kycStatus === 'NONE' ? 'Bắt đầu xác minh' : 'Xem trạng thái KYC'}
                  </Button>
                </a>
              )}
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">Tham gia</span>
                <span className="text-sm">
                  {user?.createdAt
                    ? new Date(user.createdAt).toLocaleDateString('vi-VN')
                    : '—'}
                </span>
              </div>
            </CardContent>
          </Card>

          {/* Agent details */}
          {agentProfile && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Thông tin môi giới</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Mã chứng chỉ</span>
                  <span className="text-sm font-medium">
                    {agentProfile.licenseNumber ?? 'Chưa có'}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Công ty</span>
                  <span className="text-sm font-medium">
                    {agentProfile.agency ?? 'Độc lập'}
                  </span>
                </div>
                {agentProfile.qualityScore != null && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Điểm chất lượng</span>
                    <span className="text-sm font-semibold text-primary">
                      {agentProfile.qualityScore}/100
                    </span>
                  </div>
                )}
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Xác minh</span>
                  <Badge variant={agentProfile.isVerified ? 'default' : 'outline'}>
                    {agentProfile.isVerified ? 'Đã xác minh' : 'Chưa xác minh'}
                  </Badge>
                </div>
                {agentProfile.serviceAreas.length > 0 && (
                  <div>
                    <span className="text-sm text-muted-foreground">Khu vực hoạt động</span>
                    <div className="mt-1 flex flex-wrap gap-1">
                      {agentProfile.serviceAreas.map((area) => (
                        <Badge key={area} variant="secondary">
                          {area}
                        </Badge>
                      ))}
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}
